revision:
The Element.before() method inserts a set of Node or string objects in the children list of this Element's parent, just before this Element. String objects are inserted as equivalent Text nodes.
before(param1) before(param1, param2) before(param1, param2, /* … ,*/ paramN)
Parameters:
param1, …, paramN : a set of Node or string objects to insert.
let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); let span = document.createElement("span"); p.before(span); console.log(container.outerHTML); // "<div><span></span><p></p></div>"
let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); p.before("Text"); console.log(container.outerHTML); // "<div>Text<p></p></div>"
let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); let span = document.createElement("span"); p.before(span, "Text"); console.log(container.outerHTML); // "<div><span></span>Text<p></p></div>"
this is a child Node
<div> <div id="div"> <h4>The title can be put here</h4> <p id="p">this is a child Node</p> </div> <button onclick="add()">click to add</button> </div> <script> let parent = document.getElementById("div"); console.log(parent) let para = document.getElementById("p"); function add() { const div = document.createElement("div"); div.innerHTML = "<h4>another node before</h4>"; para.before(div); } console.log(parent.outerHTML); </script>
This is JavaScript DOM before() method demo.
<div> <p id="two">This is JavaScript DOM before() method demo.</p> </div> <script> const p = document.querySelector('p#two'); const h5 = document.createElement('h5'); h5.innerText = 'JavaScript DOM - before()'; p.before(h5); </script>
<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.firstChild.before(...items); </script>