Search code examples
javascriptselectors-api

querySelectorAll changing attributes


var p = document.getElementById(e),
   nodes = p.querySelectorAll('span');

   for (var i=0; i<nodes.length; i++) {
      node = nodes[i];
      node.innerHTML = '&nbsp;';
   }

If I make after console.log(p) and console.log(nodes), i see that the changes impacted nodes, but not p. Why and how to apply to p?

If i make nodes = p.childNodes; all works fine.

So, the main question, why it works with childNodes and doesn't work with querySelectorAll?

UPDATED

Finally, adding something like below can solve the issue:

for (var k=0; k<childNodes.length; k++) {
        for (var j=0; j<nodes.length; j++) {    
            if (childNodes[k].id === nodes[j].id) {
                p.replaceChild(nodes[j],childNodes[k]);
            } 
        }   
    }

Where nodes = querySelectorAll and childNodes = p.childNodes;


Solution

  • You can simply set the innerHTML of p directly:

    p.innerHTML = '&nbsp';
    

    Please note that Element.querySelectorAll() "returns a non-live NodeList of all elements descended from the element on which it is invoked that match the specified group of CSS selectors."

    So by default, the element you are calling this on p will not be included in the returned NodeList.