66

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?

0

2 Answers 2

126

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 eligible 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():

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

Sign up to request clarification or add additional context in comments.

6 Comments

Is either of these "better practice" or more efficient? Thanks!
According to jsbench.me the first solution is almost twice as fast.
Yeah... generally, parsing HTML is going to be slow.
According to the link given (thanks) it should be better (more secure and maybe faster) to use the insertAdjacentText() method.
Maybe it's better to use nextElementSibling instead of nextSibling, because nextSibling might select a #text node instead of an element you actually want to select.
|
10

Please use the following code:

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

<script>
  var myimg = document.getElementById('myimg');
  var txt=document.createElement("span");
  txt.innerHTML="Whatever text you want to write . . .";
  if(myimg.nextSibling){
    myimg.parentNode.insertBefore(txt,myimg.nextSibling);
  }else{
    myimg.parentNode.appendChild(txt);
  }
</script>

1 Comment

You don't need to check for .nextSibling. insertBefore() will happily append the new node if the reference node is null.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.