it should be like
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li> <- Text should be red
...
<li>6</li> <- red
</ul>
I want such that when i click on the button tag, the content value of the input tag is added as li tag but for every 3rd time i added the text needs to be red how to do this in 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 nod
list.appendChild(item); // append li node to list
input.value = ''; // clear input
} else {
alert('Input text value');
}
});
})();
If I understand, you want the added li to be in red color for 3 seconds.
If so, you can add a style for the new li and remove it in setTimeout of 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>
You can choose the 3rd and 6th <li>
to be colored in red with the following CSS code :
li:nth-of-type(3) {
color: red;
}
li:nth-of-type(6) {
color: red;
}