Languages
[Edit]
EN

JavaScript - Node insertBefore() method example

0 points
Created by:
Dirask Community
6240

In this article, I would like to present documentation of the Node.insertBefore() method.

The method inserts a node before referenceNode as a child of a specified parentNode.

Quick overlook:

// newNode before referenceNode
parentNode.insertBefore(newNode, referenceNode);

// newNode at first position in parentNode
parentNode.insertBefore(newNode, parentNode.firstChild);

Note:

If the given node already exists, insertBefore() moves it from its current position to the new one.

 

1. Documentation

SyntaxparentNode.insertBefore(newNode, referenceNode)
Parameters
  • parentNode - the parent of the newly inserted node,
  • newNode┬á- the node to be inserted,
  • referenceNode┬á- the node before which┬ánewNode┬áis inserted.
Result

The method returns the added child.

DescriptionThe method inserts a node before referenceNode as a child of a specified parentNode.

Note:

If the referenceNode is null, then newNode is inserted at the end of parentNode.

2. 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>

3. 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>

JavaScript - DOM Node documentation

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