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

Can two Angular element components be utilized simultaneously on a single page in Angular 6?

Currently, I'm attempting to host independent Angular elements that can be seamlessly integrated into a non-Angular webpage. Everything works perfectly fine when there's only one element on the page, but as soon as I try to load two or more, I en ...

The requested style from ' was denied due to its MIME type ('text/html') not being compatible with supported stylesheet MIME types, and strict MIME checking is enforced

It's strange because my style.css file in the public folder works on one page but gives me an error on another. I'm not sure why it would work on one page and not on the other. The CSS is imported in index.html so it should work on all pages of t ...

What is the best way to implement an event listener for every button in a table row outcome?

I have a Rails application where I am populating a table using an @results variable, with each row representing a @result. My goal is to have buttons associated with each @result, and I'm attempting to use a JavaScript event listener for each button a ...

Using Angular with OpenStreetMap and $routeProvider allows for dynamic routing and

Check out this awesome single page app that I found: https://github.com/tombatossals/angular-leaflet-directive/blob/master/examples/simple-example.html However, I am looking to enhance it by adding a menu... <html ng-app="App"> <head> <lin ...

Oops! The provided value for the argument "value" is not a valid query constraint. Firestore does not allow the use of "undefined" as a value

I encountered an error while exporting modules from file A and importing them into file B. When running file B, the error related to Firebase Cloud Firestore is displayed. const getMailEvents = (startTime, endTime) => { serverRef = db.collection("Ma ...

Exclude the data key from form submission based on condition in React

Is it possible to omit the onSubmit value if a checkbox is selected, without requiring a specific label/input? For example, when the indefinite runTime box is checked, the key runTimeSeconds doesn't need to be included in the payload. Can this logic b ...

Populate a select list in real time with dynamically generated options

I'm facing a challenge at the moment; I am using JavaScript to dynamically generate select boxes, however, I require Ajax to populate them with options. At the moment, my code is returning undefined and I am unsure of how to proceed. While my PHP succ ...

Send both queries using JSON

I am trying to pass company information using Json, and I also want to pass the areas using the same method. However, I am encountering some issues. Can anyone provide assistance? if($_GET['method']=="get_all_companies"){ $query = "SELECT co ...

The for loop is throwing an error because the variable 'i' is not defined

I recently started using eslint and I'm in the process of updating my code to comply with my eslint configuration. module.exports = { env: { browser: true, commonjs: true, node: true, es2021: true, }, extends: 'eslint:recomm ...

Ensure the presence of an editable column within a table using a jQuery function

Within the table, the first column is editable. Upon making a change to it, I want an alert to appear indicating that a change has occurred. The check function is being called after a delay of 5000ms. Embedding Code Snippet for Reference I suspect there ...

How to Send C# Array as a Parameter to a JQuery Function

I'm currently working on passing a C# array to a JQuery function as a parameter. The C# code I have to call the function is: //Create an Array from filtered DataTable Column var GatepassIDs = defaultView.ToTable().AsEnumerable().Select(r => r ...

What is the best method for presenting nested JSON data in React using a key-value pair format?

This component serves as the product description section with tabs for both description and details. Selecting the description tab displays the product specifications in a tabular format. We are utilizing the Axios library to fetch JSON data from an API. I ...

Having trouble with the import of the directory's index file?

The code snippet in application.js indicates that the "home" imported from "./routes/index" is undefined. import {home} from "./routes/index" console.log(JSON.stringify(home, null, 4)) This is what index.js contains: export * from "./home.js" And here ...

React Material-UI is notorious for its sluggish performance

I recently started using React Material-ui for the first time. Whenever I run yarn start in my react app, it takes quite a while (approximately 25 seconds) on my setup with an i5 8400 + 16 GB RAM. Initially, I suspected that the delay might be caused by e ...

Is there a way to illuminate a complete row by simply hovering over a span within one of the columns?

If I want to change the background-color of a div with classes "row" and "highlightThisRow" when hovering over a span with the class "fromThisSpan", how can I achieve that? In a list, there are multiple rows with several columns. The span in question is l ...

"Shopping just got easier with our new drag and drop feature! Simply drag items

I want to develop a Virtual Shopping Cart system. Items will be retrieved from a database. A virtual basket will be available. Users can drag items and drop them into the basket, similar to shopping in a mall. Once the user clicks the save button, the s ...

Emulating user interaction using Prototype library - Simulate.js

I have set up a Prototype code to act as an observer, but I am facing issues triggering the observer after manually setting the value of the select element... select.observe('change', this.onChange.bindAsEventListener(this)); Initially, I tried ...

Attempting to retrieve an image from the database using ajax within a PHP script

I'm facing an issue with my code where I am attempting to retrieve an image from a database using AJAX, but it's not working as expected. Can someone please help me out? Image uploading works fine when trying to fetch the image using an anchor ta ...

Troubleshooting Timeout Problems with Selebiun Crawler in C#

I am encountering an error while running the following code. public void GetCategoriesSelenium() { string javascript = System.IO.File.ReadAllText(@"GetCategory.js"); CrawlerWebSeleniumJS.ExecuteScript("var finished;"); ...

Obtain the printed value of a button via PHP and manipulate it using JavaScript

I have a dynamic table that displays results from a database. <table id="table" class="table datatable-responsive"> <thead> <tr class="bg-teal"> <th>#</th> <th>Date & Time</th& ...