In JavaScript, apply a red color style to an appended list item every third time it is added

It should be something like this:

<ul id="list">
<li>1</li>
<li>2</li>
<li style="color: red;">3</li> <- Text should be red
...
<li style="color: red;">6</li> <- red
</ul>

I am looking to create a functionality where clicking on the button will add the content value of the input as an li tag. However, every third time I add a text, it needs to be displayed in red. How can this be achieved using JavaScript?

   <div>
      <input id="text" type="text" />
      <button id="add">Add</button>
    </div>

    <ul id="list"></ul>
      (function () {
        document.querySelector('#add').addEventListener('click', function () {
          let input = document.querySelector('#text');
          if (input.value !== '') {
            let list = document.querySelector('#list');

            let item = document.createElement('li'); // create li node
            let itemText = document.createTextNode(input.value); // create text node

            item.appendChild(itemText); // append text node to li node
            list.appendChild(item); // append li node to list

            input.value = ''; // clear input
          } else {
            alert('Please enter some text');
          }
        });
      })();

Answer №1

If my understanding is correct, you are looking to have the newly added li displayed in red color for a duration of 3 seconds.

If that's the case, you can achieve this by applying a style to the new li element and then removing it using a setTimeout function after 3 seconds:

item.classList.add("new-added-item");
setTimeout(() => {
    item.classList.remove("new-added-item");
}, 3000);

(function () {
        document.querySelector('#add').addEventListener('click', function () {
          let input = document.querySelector('#text');
          if (input.value !== '') {
            let list = document.querySelector('#list');

            let item = document.createElement('li'); // create li node
            let itemText = document.createTextNode(input.value); // create text node

            item.appendChild(itemText); // append text node to li nod
            list.appendChild(item); // append li node to list
           
            input.value = ''; // clear input
            
            item.classList.add("new-added-item");
            setTimeout(() => {
              item.classList.remove("new-added-item");
            }, 3000);
          } else {
            alert('Input text value');
          }
        });
      })();
.new-added-item {
   color: red;
}
<div>
      <input id="text" type="text" />
      <button id="add">Add</button>
    </div>

    <ul id="list"></ul>

Answer №2

If you want to highlight the 3rd and 6th list items in red, you can use this CSS snippet:

li:nth-of-type(3) {
color: red;
}

li:nth-of-type(6) {
color: red;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Best practices for referencing attributes created with the data method in a Vue component

In my application, there is a section that displays a list of users along with a search box to filter names. The user information is fetched from a database and stored in app.users. I have created a component named 'user' to show the details of e ...

Freezing in IE/Safari due to AJAX jQuery interactions

Feeling frustrated and seeking help. I am currently executing this particular script: <script type="text/javascript" charset="utf-8> jQuery(window).ready(function(){ //alert('running'); var sold = false; var l ...

Store the information in the user interface of React by converting it into a file format

Currently, I am retrieving data from an API and downloading a specific file. My goal is to store this same file in the public directory within my react application. https://i.sstatic.net/bS8Z4.png this.state = { fileDownloadUrl: null, fileName ...

To enhance user experience, consider incorporating a 'Next Page' feature after the completion of every four paragraphs,

Here is a code snippet that can be used to print 'n' number of paragraphs: <% while(rs.next()){ String para=rs.getString("poems"); %> <p> <%=para%> </p> <!-- n number of p tags are printe ...

Error: Unable to access the 'sid' property because it is undefined

I've been facing an issue where sending an SMS through Twilio's API Explorer works fine, but fails under my node installation. Despite a complete uninstall and reinstall, the problem persists. Error 7 Oct 21:28:37 - [nodemon] starting `node scr ...

Is there a way to show a 'Refresh' icon in HTML without the need to download an image through HTTP?

In my HTML/JavaScript app project, I am looking to incorporate a 'refresh' symbol without having to load an image through HTTP requests. Are there reliable methods that can achieve this across all major browsers? I came across the Unicode value: ...

Creating a Page with Python Selenium for JavaScript Rendering

When using Python Splinter Selenium (Chromedriver) to scrape a webpage, I encountered an issue with parsing a table that was created with JavaScript. Despite attempting to parse it with Beautiful Soup, the table does not appear in the parsed data. I am str ...

Insert a fresh item into the existing unordered list

Every time I enter something in the prompt, it shows up as "undefined". What I actually want is for whatever I type into the prompt to be added as a new list item. For instance, if I type "Food" in the prompt, I expect to see "Food" appear on the second li ...

Are HTML5 Track Element Cue Events Working Properly?

My goal is to dynamically assign functions to HTML5's cue.onenter events. This feature is relatively new and currently only supported in Chrome with specific flags enabled (Refer to the example on HTML5 Rocks here). However, I seem to be facing some ...

Problem with redirecting when using HTTPS

I recently implemented an SSL Certificate and made changes to the web.config file. Here is the updated code: <system.webServer> <rewrite> <rules> <rule name="removed by me" stopProcessing="true"> ...

Execute the Angular filter again when there is a change in the scope

I am currently working on an application where Users have the ability to switch between kilometers and miles for unit distances. To handle this, I created a custom filter that converts the distances accordingly: app.filter('distance', function() ...

AngularJS - automatically submitting the initial item

Is there a simple way to automatically select the first item in my ng-repeat when the list is loaded for the user? Currently, I am using ng-click, but I am unsure of how to automatically trigger a click on the first item. Here is my ng-repeat: <div n ...

Utilizing Google Places Autocomplete to tailor search outcomes

I'm currently working on customizing the output of my Google Places autocomplete code. Specifically, I want to change the displayed result when a user selects an address from the list. For example, one of the results is: '45 Alexandra Road Holi ...

Select a random object from a document and dispatch it. A Discord bot

I'm looking to enhance my bot by adding a command that retrieves a random quote from a JSON file and displays it in chat. I've already figured out how to do this using an array, but I'm not sure how to pull the quotes from a file. EDIT: ...

Iterating through an array in Javascript to create a new array filled with objects

Is there a way to iterate through an array of strings and convert them into an array of objects based on their values? For instance, if the array looks like this: [a,a,a,b,b,c,d] I aim to cycle through the array and create objects with key-value pairs t ...

Sending a multi-dimensional array to the server using PHP via POST

Similar Question: multi-dimensional array post from form I am looking to transfer data from the client to the PHP server using jQuery's $.post() method. Once the data reaches the server, I want the $_POST['myList'] variable to be in one ...

The function this.someFunction does not exist

Even though I have gone through the details of the bind requirement for methods to be associated with a React ES6 class, I am still facing challenges with this specific example: class ProductList extends React.Component { constructor(props) { super( ...

The key to creating efficient routers in Express: Don't Repeat Yourself!

Currently, I am in the process of developing a web application in the form of a network structure that involves basic CRUD operations. However, I am facing the issue of having overly large router files, prompting me to consider splitting them up. One of t ...

Troubleshooting: MongoDB/mongoose post save hook does not execute

My current setup involves the following model/schema: const InvitationSchema = new Schema({ inviter: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', required: true}, organisation: {type: mongoose.Schema.Types.ObjectId, ref: 'Orga ...

Using a custom ParcelJS plugin from the local directory

I am interested in developing a plugin to enable raw loading of a specific type of file with Parcel. According to the documentation, Parcel detects plugins published on npm with certain prefixes and automatically loads them along with their dependencies li ...