revision:
The Element.after() method inserts a set of Node or string objects in the children list of the Element's parent, just after the Element. String objects are inserted as equivalent Text nodes.
after(node1) after(node1, node2) after(node1, node2, /* … ,*/ nodeN)
Parameters:
node1,...,nodeN : a set of Node or string objects to insert.
<script> let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); let span = document.createElement("span"); p.after(span); console.log(container.outerHTML); // "<div><p></p><span></span></div>" </script>
<script> let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); p.after("Text"); console.log(container.outerHTML); // "<div><p></p>Text</div>" </script>
example: using JavaScript after() to insert a node after an element
<div> <h4>JavaScript DOM - after()</h4> </div> <script> const h4 = document.querySelector('h4'); // create a new paragraph element const p = document.createElement('p'); p.innerText = 'This is JavaScript DOM after() method demo'; // insert the paragraph after the heading h4.after(p); </script>
example: using JavaScript after() to insert multiple nodes after an element
<div> <ul> <li>Angular</li> <li>Vue</li> </ul> </div> <script> const list = document.querySelector('ul'); const libs = ['React', 'Meteor', 'Polymer']; const items = libs.map((lib) => { const item = document.createElement('li'); item.innerText = lib; return item; }); list.lastChild.after(...items); </script>
example: using JavaScript after() to insert strings
<div> <button>Donate Here</button> </div> <style> button {padding: 0.75vw 1vw; background-color: #F7DF1E; color: #000; cursor: pointer; border-radius: 50vw;} </style> <script> const button = document.querySelector('button'); button.firstChild.after(' 🧡'); </script>