Languages
[Edit]
EN

JavaScript - how to insert HTML element before element?

4 points
Created by:
Palpys
374

In this article, we would like to show you how to insert HTML element before the element using insertBefore function in JavaScript.

Quick solution:

// newElement before placeholderElement
parentElement.insertBefore(newElement, placeholderElement);

// newElement at first position in parentElement
parentElement.insertBefore(newElement, parentElement.firstChild);

 

Practical examples

Example 1 - insert before indicated element (between elements)

In this example, we will insert a new paragraph before child-2 element.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="parent">
    <p id="child-1">This is a paragraph 1.</p>
    <p id="child-2">This is a paragraph 2.</p>
  </div>
  <script>
   
    var parent = document.querySelector("#parent");
    var child1 = document.querySelector("#child-1");
    var child2 = document.querySelector("#child-2");
   
    var paragraph = document.createElement("p");
    paragraph.innerText = 'This is new paragraph placed before child-2.';
   
    parent.insertBefore(paragraph, child2);
   
  </script>
</body>
</html>

Example 2 - insert as first element

In this example, we will insert a new paragraph before all child elements inside the parent.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="parent">
    <p id="child-1">This is a paragraph 1.</p>
    <p id="child-2">This is a paragraph 2.</p>
  </div>
  <script>
   
    var parent = document.querySelector("#parent");
   
    var paragraph = document.createElement("p");
    paragraph.innerText = 'This is new paragraph placed as first.';

    parent.insertBefore(paragraph, parent.firstChild);
   
  </script>
</body>
</html>

Related posts

JavaScript - DOM Node - problems & solutions

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join