Insert a node after another element in JavaScript

June 27, 2020

after

Using after method you can insert a list of nodes or DOMString(normally strings) after a Node in which it is called.

    function getChild(className){
        let child = document.createElement("p");
        child.classList.add(className);
        return child;
    }


    let parent = document.createElement("div");

    let child1 = getChild("c-1");
    let child3 = getChild("c-3");

    parent.append(child1, child3);

    // using after
    let child2 = getChild("c-2");
    child1.after(child2);   // will add child2 after child1

Now the parent structure will be like

<div>
    <p class="c-1"></p>
    <p class="c-2"></p>
    <p class="c-3"></p>
</div>

Inserting multiple node

The after uses reset parameter to recive arguments , so you can pass as many nodes as you want to the after method.

let parent = document.createElement('div');

let child1 = getChild('child-1');
parent.append(child1);

let child2 = getChild('child-2');
let child3 = getChild('child-3');

child1.after(child2, child3);

Inserting text after a child

You can also insert a text after the child

let parent = document.createElement('div');

let child1 = getChild('child-1');
parent.append(child1);
child1.after("Inserting Text");

parent.outerHTML;
/*
    <div>
        <p class="child-1"></p>
        Inserting Text
    </div>
*/

If you don't pass any string , then it will not add anything

If you pass null then "null" string will be inserted


Please donate here, for making more tutorials.