What are the differences between NodeList and Array when using querySelectorAll()?
Answers:
querySelectorAll()is a method in the Document Object Model (DOM) API that allows you to select elements from the document using CSS selectors. The result of this method is aNodeList, which has some differences compared to a standard JavaScriptArray. Here are the key differences:1. Type
- NodeList: This is a collection of nodes, which can be element nodes (from the DOM) or other node types. It is a special object that is not a true array.
- Array: This is a standard JavaScript array object, which is a built-in, versatile data structure that can hold any type of values.
2. Methods and Properties
- NodeList:
- It has some properties (like
length) but does not have array methods likeforEach,map,filter, etc., in older browsers (although modern browsers do now supportforEachon NodeLists). - You can access items using indexed notation (e.g.,
nodeList[0]), and it supports iteration in some environments usingfor...of.
- It has some properties (like
- Array:
- It has many built-in methods (e.g.,
push,pop,map,filter, etc.) and supports all standard array operations. - Arrays can be manipulated and transformed easily since they have a richer API.
- It has many built-in methods (e.g.,
3. Live vs Static
- NodeList (from
querySelectorAll): This is a static collection of nodes. It means when you usequerySelectorAll(), you get a snapshot of the DOM at that moment. It does not automatically update when the DOM changes (e.g., if you add or remove elements that match the selector, theNodeListremains unchanged). - Array: An array contains a fixed set of elements at the time of its creation, but it can be modified by adding or removing elements.
4. Conversion
To use array methods on a
NodeList, you typically need to convert it into an array. This can be done using:Array.from(nodeList)[...nodeList](spread operator)
Example
// Using querySelectorAll const nodeList = document.querySelectorAll('div'); // NodeList properties console.log(nodeList.length); // Length of the NodeList console.log(nodeList[0]); // Accessing the first element with an index // Converting NodeList to Array to use array methods const arrayFromNodeList = Array.from(nodeList); // Now you can use array methods arrayFromNodeList.forEach((div) => { console.log(div); // Logs each div element });Conclusion
In summary, a
NodeListis a collection of DOM nodes that is static and limited in terms of methods when compared to a JavaScriptArray. For more advanced operations on the list of nodes, you would convert theNodeListto an array.