I have a complicated HTML structure that has a lot of nested divs. I want to be able to change an element that exists multiple times in the page in various places on the page but all have the same css class and html. What I currently do is:
var nodes = mutation.target.querySelectorAll(NODES_SELECTOR);
for(var i=0; i<nodes.length; i++) {
var node = nodes[i];
var newDiv = document.createElement('div');
newDiv.className = 'new-div';
newDiv.innerHTML = '<div class=\'content-div\'></div>';
/* Add various event listeners */
newDiv.addEventListener('click', function (event) {
// Do stuff
});
node.appendChild(newDiv);
}
Currently this is very slow and I assume the problem comes from manipulating the dom on every iteration.
I read this answer https://stackoverflow.com/a/18394084/8600207, But I can't figure out how to apply this for my case, as in this answer the modification happens to 1 element, not multiple like my case. Is there a way to manipulate the dom once for multiple elements? (outside the for loop) P.S.: I could use jQuery if it solves the problem, but I can't change the HTML.