Append element as sibling after element?
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.");
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>