Cover Image for jQuery insertBefore() method
103 views

jQuery insertBefore() method

The jQuery.insertBefore() method is used to insert content before each element in the set of matched elements. It allows you to move elements from their current position and place them before other elements in the DOM.

Here’s the basic syntax of the insertBefore() method:

$(newContent).insertBefore(target)

Parameters:

  • newContent: The content you want to insert before the target element(s). This can be a selector, an HTML string, a DOM element, or a jQuery object representing the content to be inserted.
  • target: The target element(s) before which the newContent will be inserted. This can be a selector, a DOM element, or a jQuery object representing the target element(s).

Return Value:
The insertBefore() method returns the original jQuery object, allowing for method chaining.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery insertBefore() Method Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="target">
        <p>Original content</p>
    </div>

    <script>
        $(document).ready(function() {
            // Create new content as a jQuery object
            var newContent = $("<p>Inserted content</p>");

            // Insert the new content before the target element
            newContent.insertBefore(".target");
        });
    </script>
</body>
</html>

In this example, we use the insertBefore() method to insert a new <p> element with the text “Inserted content” before the element with the class “target.”

The resulting HTML will be:

<div class="target">
    <p>Inserted content</p>
    <p>Original content</p>
</div>

As you can see, the new content is successfully inserted before the target element.

You can use insertBefore() to move elements from one location to another in the DOM dynamically, or to add new content before existing elements.

Keep in mind that the target element(s) will remain in their original location after being inserted. If you want to move elements to a new location and remove them from their current position, you can use the appendTo() method in a similar way.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS