insertBefore() method, we learned earlier to add an element before, can also be used to insert an element after an HTML node. For this purpose, we need to use the element's
nextSibling property that returns a reference to an immediate node at the same tree level.
Here is an example:
// create a new element const elem = document.createElement('p'); // add text elem.innerText = 'I am a software engineer.'; // grab target element reference const target = document.querySelector('#intro'); // insert the element after target element target.parentNode.insertBefore(elem, target.nextSibling);
insertBefore() method works in all modern and old browsers including Internet Explorer 6 and higher.
If you want to insert an HTML string after a certain element in the DOM, use the
insertAdjacentHTML() instead, like below:
// insert HTML string after target element target.insertAdjacentHTML('afterend', '<p>I am a software engineer.</p>');
insertAdjacentHTML() method automatically parses the given string as HTML and inserts the resulting elements into the DOM tree at the given position. Take a look at this guide to learn more about it.
ES6 introduced a new method called
after() to insert an element right after an existing node in the DOM. Just call this method on the element you want to insert an element after, and pass the new element as an argument:
// insert the element after target element target.after(elem);
Just like the
after() only works in modern browsers specifically in Chrome, Firefox, and Opera. At the moment, Safari and Internet Explorer don't support this method. However, you can use a polyfill to bring the support up to IE 9 and higher.
👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, ☕ Buy me a coffee (cost $5) .
Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.