How to add the previous element to current jQuery selection?

To add the previous element to current jQuery selection, use the insertBefore() method. This method inserts selected elements before the specified target element in the DOM.

Syntax

The basic syntax of the insertBefore() method is ?

$(content).insertBefore(target)

Where content is the element to be inserted and target is the element before which the content will be placed.

Example

You can try to run the following code to learn how to work with insertBefore() method ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("<span>Demo text </span>").insertBefore("p");
            });
        });
    </script>
</head>
<body>
    <button>Insert</button>
    <br>
    <p>This is a paragraph.</p>
</body>
</html>

When you click the "Insert" button, the span element with "Demo text" will be inserted before the paragraph element.

How it Works

The insertBefore() method works by ?

  • Creating or selecting the content to be inserted
  • Identifying the target element using a selector
  • Placing the content immediately before the target element in the DOM tree

Conclusion

The insertBefore() method is a powerful jQuery function that allows you to dynamically add elements before existing elements in your HTML document, making it useful for creating interactive web pages.

Updated on: 2026-03-13T18:48:20+05:30

666 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements