How to insert HTML before elements in JavaScript without jQuery?
Use the before method to insert an element new element before a specific element.
And use The insertBefore() method to inserts a node as a child, right before an existing child, which you specify.
JavaScript insert before method examples
Let’s see 2 HTML example codes of JS insertbefore and before the method.
Before method Add a new element
<!DOCTYPE html>
<html>
<body>
<div id="div1"> Div First</div>
<script>
// Parent Element
const ele = document.getElementById("div1");
const newEl = document.createElement("div");
newEl.id = "foo";
ele.before(newEl);
</script>
</body>
</html>
Output:
insertBefore method adds a new child
Insert a new “<li>” element before the first child element of an “<ul>”element:
<!DOCTYPE html>
<html>
<body>
<ul id="tea">
<li>Green Tea</li>
<li>Black Tea</li>
</ul>
<script>
var newEl = document.createElement("li");
var textnode = document.createTextNode("Ginger Tea");
newEl.appendChild(textnode);
var list = document.getElementById("tea");
list.insertBefore(newEl, list.childNodes[0]);
</script>
</body>
</html>
Another example code
<script>
let menu = document.getElementById('menu');
// create a new li node
let li = document.createElement('li');
li.textContent = 'Home';
// insert a new node before the first list item
menu.insertBefore(li, menu.firstElementChild);
</script>
Output: First example output
Do comment if you have any doubts and suggestions on JS insertbefore() method examples.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version