javascripthtmldom

Append element as sibling after element?


How do I add a text after an HTML element using pure Javascript? There is appendChild but this adds it within the element. I would instead like to add it as a sibling after the element like this:

<img id="myimg" src="..." />

<script>
  var myimg = document.getElementById('myimg');
  myimg.appendAFTER('This is my caption.'); //pseudo-code and doesn't really work
</script>

I would like to end up with this:

<img id="myimg" src="..." />
This is my caption.

What is the Javascript equivalend of after() from jQuery?


Solution

  • The fastest way to insert a node is probably Node.insertBefore() and Node.nextSibling, as it doesn't involve HTML parsing.

    const referenceNode = document.querySelector("div");
    // caption could be any node, e.g.: element, text, comment, etc.
    const caption = document.createTextNode("This is my caption.");
    referenceNode.parentNode.insertBefore(caption, referenceNode.nextSibling);
    <div>Reference Node</div>

    If you're just injecting text, you could use Element.insertAdjacentText()

    const referenceNode = document.querySelector("div");
    referenceNode.insertAdjacentText("afterend", "This is my caption.");
    <div>Reference Node</div>

    If you need to inject markup, you could use Element.insertAdjacentHTML() (fiddle):

    const referenceNode = document.querySelector("div");
    referenceNode.insertAdjacentHTML("afterend", "<b>This is my caption.</b>");
    <div>Reference Node</div>