47

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
  • 7,819
  • 9
  • 46
  • 75
TruMan1
  • 30,176
  • 50
  • 162
  • 301

2 Answers2

87

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.");
elliottregan
  • 1,175
  • 1
  • 12
  • 31
canon
  • 38,844
  • 9
  • 71
  • 94
7

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
  • 794
  • 6
  • 17
  • 5
    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