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?
First, select the ul element by its id ( menu ) using the getElementById() method. Second, create a new list item using the createElement() method. Third, use the insertAfter () method to insert a list item element after the last list item element.
append() allows you to also append string objects, whereas Node. appendChild() only accepts Node objects. Element. append() has no return value, whereas Node.
To create a new element to be inserted at the end of a parent node, first use createElement to create it and then appendChild() for the newly-created element. The appendChild() method also works on existing child nodes, using which you can move them to new positions within the document.
To append multiple child elements with JavaScript, we can use the append method. Then we write: const listElement = document. querySelector('ul') const listItem = document.
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>
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.");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With