I am still new to js so I can’t handle the following problem: this line creates an item in a bulleted list.

function addLi(nameGroup, classGroup) { var elem = document.getElementById("item"); var div = document.createElement("li"); div.setAttribute('class', classGroup); div.setAttribute('id', 'item'); div.innerHTML = nameGroup.toString(); elem.parentNode.appendChild(div); } 

But after creating an element, I cannot attach a click() event to it. When I added the same element in the html itself and then created a new one, the first one responded to clicks, and the second did not (

I have already tried different ways to add: insertBefore, appendChild

  • div.setAttribute('id', 'item'); In this line you add an element to the element. if two identical elements add the same ID, then the second will not react, for ID must be unique for each element. - lexxl
  • @lexxl thanks, now I will try. Listen, what is the alternative or how can I write on js: $('.sidebar__items').find(li) ? - Artem Holinka
  • document.querySelectorAll('.sidebar__items li') - querySelectorAll returns a list of elements within the document (the search is performed within the specified element) that correspond to the specified selector group. - lexxl
  • @lexxl changed div.setAttribute('id', classGroup); but still does not respond to pressing ( classGroup constantly changing). I appeal to the item class. Maybe the problem is how I added a new block to the page? I js when looking for him, you simply do not see? - Artem Holinka
  • @ ArtemGolinka yes, when you create a new element there are no listeners on it, hang div.addEventListener('click', addLi) in your method after elem.parentNode.appendChild(div); - Vasily Barbashev

1 answer 1

You do not hang handler after adding a new container. Therefore, the click event is not triggered.

Add an event subscription to the very end of your method:

 div.addEventListener('click', addLi) 

Then the newly created div will look at the same method that created it, and call it.