Is it possible to append an element to a JavaScript nodeList?

frequent picture frequent · Nov 19, 2013 · Viewed 21k times · Source

I'm generating content dynamically, so I'm often ending up with documentFragments which I'm querying using querySelectorAll or querySelector returning a nodeList of elements inside my documentFragment.

From time to time I would like to add an item to a list, but I can't find anything online on whether this is even possible.

I tried it like this:

 document.querySelectorAll(".translate").item(length+1) = document.createElement("div");

and this:

 document.querySelectorAll(".translate").shift(document.createElement("div"));

But both don't work (as expected)

Question:
Is it possible to manually add elements to a NodeList? I guess, not but asking nevertheless.

Thanks for some insights?

EDIT:
So more info: I'm generating a block of dynamic content, which I want to append to my page. By default the block is in English. Since the user is viewing the page in Chinese, I'm running a translator on the dynamic fragment, BEFORE appending it to the DOM. On my page, I also have an element, say a title, which should change depending on the dynamic content being added. My idea was to do this in one step = try to add an element to my nodeList. But from writing it now... I guess not possible :-)

Answer

Tibos picture Tibos · Nov 19, 2013

EDIT: As @Sniffer mentioned, NodeLists are read-only (both the length property and the items). You can manipulate everything else about them, like shown below, but it's probably better to convert them to arrays instead if you want to manipulate them.

var list = document.querySelectorAll('div');
var spans = document.querySelectorAll('span');

push(list, spans);
forEach(list, console.log); // all divs and spans on the page

function push(list, items) {  
  Array.prototype.push.apply(list, items);
  list.length_ = list.length;
  list.length_ += items.length;
}

function forEach(list, callback) {
  for (var i=0; i<list.length_; i++) {
    callback(list[i]);
  }
}

It would probably be a better idea to turn the NodeList to an array instead (list = Array.prototype.slice(list)).

var list = Array.prototype.slice.call(document.querySelectorAll('div'));
var spans = Array.prototype.slice.call(document.querySelectorAll('span'));

list.push.apply(list, spans);
console.log(list); // array with all divs and spans on page