JavaScript

JavaScript insertBefore() Method

Sometimes we need to insert an element at a specific position, or we need to insert an element before any particular element. At that time we can use JavaScript insert before method.

The InsertBefore() Method

JavaScript insertBefore() method inserts a node at the specified position between HTML DOM elements.

Also Read: JavaScript appendChild() Method

Example

Let’s consider we need to insert an element at 2nd position in the list.

<!DOCTYPE html>
<html>
<head>
  <title>Errorsea - JavaScript Insert Before</title>
</head>
<body>

<ul id="languages">
  <li>Java</li>
  <li>PHP</li>
  <li>Python</li>
</ul>

<button >

Note: Here we take 3rd child node’s position to insert a node at 2nd position.

Explanation

  • First, we create a new <li> element using document.createElement() function.
  • Then we set it’s innerHTML value to “JavaScript”
  • Then we append newly created <li> element in the list at 2nd position.

Conclusion

I hope now you have a complete understanding of the insertBefore() method in JavaScript. The main use of the insertBefore() method is to insert an element at a specific position.

Enjoy Scripting 🙂

Nachiket Panchal

Founder & Administrator of `errorsea` Having interest in Programming & Technology.

Recent Posts

5 Important Things To Know About WordPress Before You Use It

There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…

3 years ago

How to Install MySQL on Your PC in 3 Easy Steps

In this tutorial, I'm going to show you how to install MySQL on your computer.…

4 years ago

Download and Install Turbo C++ for Windows 10 (Full Installation Guide)

Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…

5 years ago

PHP .HTACCESS Redirects

We can redirect any webpage to any other or redirect the whole domain or website…

5 years ago

PHP Redirect Pages

There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…

5 years ago

PHP Include & Required

Include files in PHP are used in appending various global or config files. We can…

5 years ago