JavaScript provides a range of methods that can be used to manipulate the DOM. You've already learned about the basics, so this topic dives deeper into the more advanced options. These methods offer greater flexibility when adding and replacing elements on a webpage. Read on to learn how you can utilize them in your web applications.
Node insertion methods
Have you ever wondered about the different ways to add nodes to the DOM? In this section, you'll learn about a group of methods that can be used to insert elements in various positions. Take a look at the descriptions of these insertion methods below:
before(): adds a node right before the element.prepend(): adds a node as the first child of the element.append(): adds a node as the last child of the element.after(): adds a node right after the element.
The before(), prepend(), append(), and after() methods can also be used to add several elements or text nodes at once.
You can see examples of how to use these methods below:
document.body.innerHTML = "<ul id='list'><li>The node</li></ul>"; // creates a list
let list = document.getElementById("list");
let startNode = document.createElement("p");
startNode.textContent = "The start";
list.before(startNode); // adds startNode right before the list
let firstNode = document.createElement("li");
firstNode.textContent = "The first node";
list.prepend(firstNode); // adds firstNode as the first child of the list
let lastNode = document.createElement("li");
lastNode.textContent = "The last node";
list.append(lastNode); // adds lastNode as the last child of the list
let endNode = document.createElement("p");
endNode.textContent = "The end";
list.after(endNode); // adds endNode right after the listAnd this is what the resulting HTML code looks like following all these actions:
<p>The start</p>
<ul id='list'>
<li>The first node</li>
<li>The node</li>
<li>The last node</li>
</ul>
<p>The end</p>insertAdjacentHTML()
What if you need to add HTML content instead of a node? In this case, you should use the insertAdjacentHTML() method. It works in a similar way to those described in the previous section but accepts two arguments: a position value and the HTML content itself. This method parses the HTML and inserts the resulting node into the DOM in the required place. You can specify four different types of insertion:
"beforebegin": adds the HTML content right before the element."afterbegin": adds the HTML content as the first child of the element."beforeend": adds the HTML content as the last child of the element."afterend": adds the HTML content right after the element.
The following examples show how to use this method:
document.body.innerHTML = "<ul id='list'></ul>"; // creates a list
let list = document.getElementById("list");
// adds HTML right before the list
list.insertAdjacentHTML("beforebegin", "<p>beforebegin</p>");
// adds HTML as the first child of the list
list.insertAdjacentHTML("afterbegin", "<li>afterbegin</li>");
// adds HTML as the last child of the list
list.insertAdjacentHTML("beforeend", "<li>beforeend</li>");
// adds HTML right after the list
list.insertAdjacentHTML("afterend", "<p>afterend</p>");You can see the result below:
<p>beforebegin</p>
<ul id="list">
<li>afterbegin</li>
<li>beforeend</li>
</ul>
<p>afterend</p>replaceWith()
Sometimes you need to change a node that's already on the webpage. The replaceWith() method is designed for this purpose — it replaces the element with the given node, as shown below:
// creates a container with a header inside
document.body.innerHTML = "<div id='container'><h1 id='header'>An old header.</h1></div>";
let newHeader = document.createElement("h2");
newHeader.textContent = "A new header!";
let header = document.getElementById("header");
header.replaceWith(newHeader); // replaces the header with a new element
let container = document.getElementById("container");
console.log(container); // <div id='container'><h2>A new header!</h2></div>cloneNode()
You can use the cloneNode() method to return a copy of the given node with all its attributes. It accepts a logical argument: if it's true, the method creates a copy that includes the original element's child nodes, and if it's false, only the element itself is copied.
To append a cloned node to the DOM, you also need to use one of the insertion methods. By default, the cloneNode() method does not add an element to the document.
Take a look at the following example:
document.body.innerHTML = "<ul id='list'><li id='item'>Clone me</li></ul>"; // creates a list
let list = document.getElementById("list");
let item = document.getElementById("item");
let newItem = item.cloneNode(true); // clones the item (including the inner text node)
list.append(newItem); // appends newItem to the list
console.log(list); // <ul id="list"><li id="item">Clone me</li><li id="item">Clone me</li></ul>Best practices
Validate HTML content: When using
insertAdjacentHTML(), ensure the HTML content you're inserting is valid and sanitized, especially if it's user-generated content. This helps prevent security vulnerabilities like Cross-Site Scripting (XSS).Avoid frequent DOM manipulations in loops: Repeated DOM manipulations within loops can be costly in terms of performance. Instead, consider building the changes in a document fragment or string, and then insert them into the DOM all at once.
Use cloneNode() sparingly: While cloning nodes can be useful, avoid overusing
cloneNode()with deep cloning (cloneNode(true)) in performance-critical applications, as it can lead to unnecessary memory consumption if not managed properly.
Conclusion
In this topic, you have learned about advanced techniques for inserting nodes into the DOM: the before(), prepend(), append(), and after() methods. They offer the flexibility to place elements in several different locations. You can add a node as the first or last child of the parent node and right before or after the given node. You also found out about insertAdjacentHTML(). This method is used for inserting HTML content and works in a similar way to the node insertion methods. Lastly, don't forget that you can utilize the replaceWith() and cloneNode() methods for replacing and copying nodes.
Read more on this topic in Get Things Done with getElementsByType on Hyperskill Blog.