Introduction to Javascript after() and before() method
after() insert an element node to the DOM after the child element
syntax of the after()
Selector.after(node)
//or
Selector.after(node1, node2, ... nodeN)
Use :
h1.after(p) // <p></p><h1></h1>
//or
Selector.after(str1, str2, ... strN)
//example
const li_items = ['a1', 'a2', 'a3'];
const items = li_items.map((li_items) => {
const item = document.createElement('li');
item.innerText = li_items;
return item;
});
ul.firstChild.after(...items); //<ul><li>firstChild</li><li>a1</li><li>a2</li><li>a3</li></ul>
whereas, ul.firstChild is the first child of UL Element
before() allow insert one or more nodes before the element
syntax of the before()
Selector.before(node)
//or
Selector.before(node1, node2, ... nodeN)
Use :
h1.before(p) // <h1></h1><p></p>
//or
Selector.before(str1, str2, ... strN);
const li_items = ['a1', 'a2', 'a3'];
const items = li_items.map((li_items) => {
const item = document.createElement('li');
item.innerText = li_items;
return item;
});
ul.firstChild.before(...items); //<ul><li>a1</li><li>a2</li><li>a3</li><li>firstChild</li></ul>
whereas, ul.firstChild is the first child of UL Element
Supported Browsers:
Google Chrome 54+
Edge 17+
Firefox 49+
Opera 39+
Safari 10+
Internet Explorer not supported