2

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

Lionel T
  • 1,559
  • 1
  • 13
  • 30
  • Take a look at the `MutationObserver`: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver – thomaux Dec 01 '14 at 08:56
  • 1
    Thanks! Also I'm trying MutationEvents (and reading that there are some pref issues): http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers – Lionel T Dec 01 '14 at 09:36
  • If I'm not mistaken, the MutationObserver is a replacement of the MutationEvent, so you should check if the browsers you're targeting support the feature! – thomaux Dec 01 '14 at 10:30
  • in last FF, Safari and Chrome MutationEvent works well. – Lionel T Dec 01 '14 at 17:52

0 Answers0