How can I insert an element after another element in JavaScript without using a library?
I know about insertBefore(), but is there a native way to do this?
I need a solution for JavaScript insertAfter() functionality without using jQuery or other libraries.
Hi,
To achieve javascript insertafter functionality without using a library like jQuery, JavaScript doesn’t provide a direct insertAfter() method.
However, you can accomplish this with some workarounds. you can use parentNode.insertBefore() with nextSibling : You can insert an element after another element by using insertBefore() with the target element’s nextSibling. If the target has no nextSibling, it will insert at the end of the parent node.
function insertAfter(newElement, targetElement) {
targetElement.parentNode.insertBefore(newElement, targetElement.nextSibling);
}
In this approach, insertBefore() is used with nextSibling to simulate an javascript insertafter behavior.
If the target element is the last child of its parent, simply appending the new element with appendChild() works.
function insertAfter(newElement, targetElement) {
if (targetElement.nextSibling) {
targetElement.parentNode.insertBefore(newElement, targetElement.nextSibling);
} else {
targetElement.parentNode.appendChild(newElement);
}
}
This solution combines insertBefore() and appendChild() to handle cases where the target element is the last child.
In modern JavaScript, the after() method can be used to insert an element directly after another element. This method works with most modern browsers.
function insertAfter(newElement, targetElement) {
targetElement.after(newElement);
}
This is the simplest approach for javascript insertafter if you are using a modern browser, as it directly provides the desired functionality.