update querySelectorAll nodeList after added element dynamically

4.4k views Asked by At

I have a function that select all elements inside an specific class through document.querySelectorAll(theClass + ' > *'); but need to listen in case some element is added inside this DOM block but after fired the function. Here is an example:

function controlElems(cl){
  var nl = document.querySelectorAll(cl + ' > *');
  console.log(nl.length);
}

document.addEventListener("DOMContentLoaded", function() {
  var list = document.querySelector('.list');
  controlElems('.list');

  // This element added after controlElems() 
  // won't be inside the nodeList

  var newElm = document.createElement('li');
  newElm.id = "id5";
  newElm.innerHTML ="Item 5: after";
  list.appendChild(newElm);
});

example also here

0

There are 0 answers