23

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 :-)

frequent
  • 27,643
  • 59
  • 181
  • 333

6 Answers6

24

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
Tibos
  • 27,507
  • 4
  • 50
  • 64
  • interesting. Did not think this was possible. – frequent Nov 19 '13 at 15:48
  • 1
    Helpful answer, and a very helpful technique. In modern JavaScript you can also use `Array.from(document.querySelectorAll('div'))` which is more intuitive. You can probably guess which browser doesn’t support it, though it’s easy to polyfill: `if(!Array.from) Array.From=function(data) { return Array.prototype.slice.call(data); };` – Manngo Jul 03 '18 at 05:28
19

1. DOM approach

I have another suggestion. You can select multiple nodes by query separator (,), This code will save all h2 and h3 tags in nodes variable:

var nodes = document.querySelectorAll('h2, h3');

Reference: MDN: Spread syntax (...)


2. ES6 approach

If you are not using dom. You can use ... ES6 operator which converts NodeList to Array.

var nodes = [
    ...document.querySelectorAll("h1"),
    ...document.querySelectorAll("h2")
];

3. ES5 approach

let h1s = Array.prototype.slice.call(document.querySelectorAll("h1"));
let h2s = Array.prototype.slice.call(document.querySelectorAll("h2"));
let nodes = h1s.concat(h2s)
Gerold Broser
  • 14,080
  • 5
  • 48
  • 107
Amir Fo
  • 5,163
  • 1
  • 43
  • 51
7

Unlike previously described element selection methods, the NodeList returned by querySelectorAll()is not live: it holds the elements that match the selector at the time the method was invoked, but it does not update as the document changes. [1]

The NodeList in this case is not alive, so if you add/remove anything to/from it, then it won't have any effect on the document structure.

A NodeList is a read-only array-like object. [1]

[1]: JavaScript: The Definitive Guid, David Flanagan

Ibrahim Najjar
  • 19,178
  • 4
  • 69
  • 95
  • I know that. I have a `documentFragment` which I'm QSA-ing to get my nodeList. This list I need to translate (see comment above), PLUS my element X which is not part of the fragment. Question is how to handle X? – frequent Nov 19 '13 at 15:21
  • 1
    @frequent from the same reference, `A NodeList is a read-only array-like object`. – Ibrahim Najjar Nov 19 '13 at 15:24
1

Use ES6 Set():

var elems = new Set([
    ...document.querySelectorAll(query1),
    ...document.querySelectorAll(query2)
]);
Dmitry Shashurov
  • 1,148
  • 13
  • 11
0

To not get into technicalities with array methods it can sometimes be more readable to make a list of node names and loop over the list.

In this example I assign the same event handler to all buttons in two different radio button groups (where each button in the group has the same name):

<div>
    <input type="radio" name="acmode" value="1" checked="checked">Phase<br>
    <input type="radio" name="acmode" value="2">Ssr<br>
    <input type="radio" name="acmode" value="3">Relay<br>
</div>
<div>
    <input type="radio" name="powermode" value="0"  checked="checked">Manual<br>
    <input type="radio" name="powermode" value="1">Automatic<br>
</div> 

Sample event handler:

var evtRbtnHandler =
    function rbtnHandler() {
        document.getElementById("response11").innerHTML = this.name + ": " + this.value;
    }

And assigning:

var buttongroup = ["acmode", "powermode"];
buttongroup.forEach(function (name) {
    document.getElementsByName(name).forEach(function (elem) {
        elem.onclick = evtRbtnHandler;
    });
});

In any case once you get your hands on each single item it can be pushed() to an array using human readable code.

flodis
  • 1,123
  • 13
  • 9
0

NodeLists are readonly, so we cannot mutate it directly. But here is how you can add new item to a NodeList:

let list = document.querySelector("#app").childNodes; // node list
list = list[0]; // selecting the first element in node list
list.parentNode.appendChild(/* new elements */); // adding to parent of current node
Gerold Broser
  • 14,080
  • 5
  • 48
  • 107
Obaydur Rahman
  • 723
  • 5
  • 15