Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append element as sibling after element? [duplicate]

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?

like image 292
TruMan1 Avatar asked Jan 29 '14 04:01

TruMan1


People also ask

How do you add an element after another element?

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.

What is the difference between append and appendChild?

append() allows you to also append string objects, whereas Node. appendChild() only accepts Node objects. Element. append() has no return value, whereas Node.

How do you append a child to an element?

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.

Can you append multiple elements in JavaScript?

To append multiple child elements with JavaScript, we can use the append method. Then we write: const listElement = document. querySelector('ul') const listItem = document.


2 Answers

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> 
like image 30
kcak11 Avatar answered Sep 21 '22 14:09

kcak11


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."); 
like image 145
canon Avatar answered Sep 23 '22 14:09

canon