57

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?

Ishan Jain
  • 8,063
  • 9
  • 48
  • 75
TruMan1
  • 33,665
  • 59
  • 184
  • 335

2 Answers2

105

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.");
canon
  • 40,609
  • 10
  • 73
  • 97
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>
kcak11
  • 832
  • 7
  • 19
  • 8
    You don't need to check for `.nextSibling`. `insertBefore()` will happily append the new node if the reference node is `null`. – canon Jan 29 '14 at 06:00