The NodeList is one of numerous tools in JavaScript that may be used to interact with the Document Object Model. A NodeList is a collection of nodes that may be retrieved using methods like document.querySelectorAll() selects elements from the DOM.
This article will look at seven different techniques to put NodeList into the DOM using JavaScript. By the end, you'll grasp how to efficiently manipulate NodeLists.
Explore remote JavaScript roles with Index.dev and work on top global projects from anywhere.
1. Understanding NodeLists
Before we go into the methods for inserting NodeLists, we first define what they are. A NodeList is an array-like object that holds a collection of nodes, which may comprise items, text nodes, and comments.
There are two sorts of node lists: live and static.
- When the document changes, the Live NodeLists are automatically updated. For example, childNodes produces a live NodeList that includes all of an element's child nodes.
- Static NodeLists do not alter once they are formed. For example, document.querySelectorAll() returns a static NodeList containing all matched items at the time the function is invoked.
Here's a brief example of making a NodeList with document.querySelectorAll():
const items = document.querySelectorAll('.item'); // Static NodeList
console.log(items); // Logs a NodeList of elements with class "item"
2. Using appendChild()
The appendChild() function is a straightforward way to inject a node into the DOM. This function creates a single node as the final child of a given parent node. However, if you have a NodeList, you must loop over it to add each node manually.
Example Code
const items = document.querySelectorAll('.item');
const parent = document.getElementById('parent');
items.forEach(item => {
parent.appendChild(item); // Appends each item to the parent
});While appendChild() is straightforward, it only allows inserting one node at a time. If you have a NodeList, it can be a bit cumbersome.
Explore More: How to Generate Random Objects in JavaScript?
3. Leveraging append()
The append() technique is more flexible than appendChild() since it may add several nodes and strings to the DOM in a single call. It accepts several inputs, giving it a good option for adding NodeLists.
Example Code
const items = document.querySelectorAll('.item');
const parent = document.getElementById('parent');
parent.append(...items); // Using spread operator to append all itemsIn this example, the spread operator ... is used to unpack the NodeList into individual nodes. This approach is more concise and efficient when inserting multiple nodes.
4. Utilizing insertBefore()
The insertBefore() method allows you to insert a node before a specified reference node. This method is handy when you need to insert nodes at a specific position in the DOM.
Example Code
const items = document.querySelectorAll('.item');
const parent = document.getElementById('parent');
const referenceNode = document.getElementById('reference');
items.forEach(item => {
parent.insertBefore(item, referenceNode); // Inserts before the reference node
});In this case, each item from the NodeList is inserted before the specified reference node. This method provides more control over where nodes are inserted in the DOM.
5. Employing replaceChild()
The replaceChild() method replaces a child node with a new node. You can use this method to replace existing nodes in the DOM with nodes from a NodeList.
Example Code
const items = document.querySelectorAll('.item');
const parent = document.getElementById('parent');
const existingNode = document.getElementById('existing');
items.forEach(item => {
parent.replaceChild(item, existingNode); // Replaces the existing node with the item
});This strategy is handy when you want to change individual nodes without eliminating them totally. It is important to note that this will only replace the first occurrence of the existingNode with the first item in the NodeList.
6. Using innerHTML for Insertion
You may also utilize the innerHTML attribute to add NodeLists to the DOM. This approach is highly strong, but it comes with certain limitations. When you set innerHTML, the browser parses the string and replaces the element's whole content. This implies that any current event listeners on the child nodes will be deleted.
Example Code
const items = document.querySelectorAll('.item');
const parent = document.getElementById('parent');
// Convert NodeList to HTML string
let htmlString = '';
items.forEach(item => {
htmlString += item.outerHTML; // Create HTML string
});
parent.innerHTML = htmlString; // Set the innerHTMLThis approach is simple, but it should be used with caution because it might cause performance concerns when manipulating huge DOMs. Always think about the ramifications of replacing old nodes.
7. The Power of Document Fragments
Using Document Fragments is an effective approach to inject many nodes into the DOM. A Document Fragment is a lightweight container that can hold a number of nodes. You can create a Document Fragment with nodes from a NodeList and then add it to the DOM in one step.
Example Code
const items = document.querySelectorAll('.item');
const parent = document.getElementById('parent');
const fragment = document.createDocumentFragment(); // Create a Document Fragment
items.forEach(item => {
fragment.appendChild(item.cloneNode(true)); // Clone and append each item
});
parent.appendChild(fragment); // Append the fragment to the parentBy using a Document Fragment, you minimize the number of reflows and repaints in the browser, making this method the most efficient for inserting large sets of nodes.
Explore More: 10 Steps to Migrate an Existing React Project to the NextJS
Conclusion
In this blog, we explored seven ways to insert NodeLists into the DOM using JavaScript. From simple methods like appendChild() to more advanced techniques using Document Fragments, each method has its advantages and use cases.
- appendChild() for simple insertion.
- append() for multiple nodes in one go.
- insertBefore() for precise positioning.
- replaceChild() for replacing nodes.
- innerHTML for setting content dynamically.
- Document Fragments for efficient batch insertion.
Each method can be useful depending on the situation. Consider performance implications and maintainability when choosing a method for your project. Happy coding!
For Developers: Explore remote JavaScript roles with Index.dev and work on top global projects from anywhere.
For Clients: Hire skilled JavaScript developers with Index.dev to build scalable, efficient projects.