Append element as sibling after element?

dom, html, javascript

Solution

Check out `Node.insertBefore()` and `Node.nextSibling` (fiddle):

var myimg = document.getElementById('myimg');
var text = document.createTextNode("This is my caption.");
myimg.parentNode.insertBefore(text, myimg.nextSibling)

or `Element.insertAdjacentHTML()` (fiddle):

var myimg = document.getElementById('myimg');
myimg.insertAdjacentHTML("afterend", "This is my caption.");

Problem

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?

Original source

Related problems