16 of 17 menu

The Error of Incorrect Parent Clearing in JavaScript

Let's say we have a certain list. Let's say that upon clicking a button, we want to form this list anew each time, clearing its previous content. Beginners often make the mistake of trying to come up with some complex solution. Let's look at a simple option.

Let's say we get the list into a variable:

let ul = document.querySelector('ul');

Let's also say we get the button:

let btn = document.querySelector('button');

Let's say that upon clicking the button, our list is filled with some values. For the example, I took a random value, corresponding to the current second:

btn.addEventListener('click', function() { let rand = new Date.getSeconds(); for (let i = 0; i <= rand; i++) { let li = document.createElement('li'); li.textContent = i; ul.append(li); } });

In the code above, new list items will be added after the existing ones. But we would like the previous items to be removed first. The solution is simple - we just need to clear the text of our ul tag:

btn.addEventListener('click', function() { ul.textContent = ''; // clear the list let rand = new Date.getSeconds(); for (let i = 0; i <= rand; i++) { let li = document.createElement('li'); li.textContent = i; ul.append(li); } });
plkasvazhi