Languages
[Edit]
EN

JavaScript - insert HTML element before element

4 points
Created by:
Palpys
764

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

Quick solution:

parentElement.insertBefore(newElement, someElement);

Hint: by using parentElement.insertBefore(newElement, parentElement.firstChild) we can add new element at first position.

 

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>

 

See also

  1. JavaScript - Node insertBefore() method example 

Alternative titles

  1. JavaScript - insertBefore() method example
  2. JavaScript - add HTML element before (like append)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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