What is a nodeList object in Javascript?
As its name says is a list we from the DOM. Documentation. This includes the attributes and text of the nodes.
How can I access elements from a nodeList?
Like any data collection, access each node through an index to the element you want. One of the most common ways to do this is with a for
.
var list = document.querySelectorAll('input[type=checkbox]');
for (var checkbox of list) {
checkbox.checked = true;
}
Almost all of a array works in it, but it’s a collection with another structure. And it does not provide access in dictionary form, so you cannot access the names of the elements found in the selected element.
document.querySelectorAll("p")[1] //pega o segundo elemento da lista de nós de p
I put in the Github for future reference.
It is possible to convert it to a Array
and access it this way. The array is static, or the data does not change. The nodeLIst
is alive, so because it is a direct reference to the GIFT, as the GIFT is modified by the page the content found there is reflected in these changes of the GIFT. Not all iterations with a variable that has a nodeList
will be equal.
What is the difference between a conventional array and a nodeList?
A array all positions in sequence
What is its use?
It stores a collection of DOM elements selected by one of the functions of the browser selecting what you want. There you can do various manipulations on each of these elements. Usually it is useful when you need to do operations on all elements or at least a portion of them. Understand that manipulating doesn’t have to be moving, it could just be checking. What you can do individually with an element in this case can do generally.
The most common function that returns this collection is the document.querySelectorAll()
. The estate Node.childNodes
also has a reference to this.
I do not understand why the downvote. Could you put in the comments please? So I can improve the question, if that’s the case, or if it’s a duplicate.
– João Pedro Schmitz
In short, it is a list of nodes (whether they are elements, texts or even comments), the same as a common array, the difference is in
NodeList.prototype
andArray.prototype
, the utility is that it is a special array for a specific function, but you will hardly create one of them directly– Costamilam
Giving a common example of point 3 cannot use
map
in aNodeList
while an array can. Something likedocument.querySelectorAll("li").map(x => x.textContent)
to obtain an array of texts from the various<li>
does not work because it is not an array.– Isac