Skip to content
Related Articles

Related Articles

Improve Article

How to insert an object before all paragraphs using jQuery ?

  • Last Updated : 31 Mar, 2021

jQuery is a Javascript library to ease the task of web developers. Developers can use the Jquery library rather than using Javascript in their code. Jquery provides a lot of good features like DOM manipulation, event handling, AJAX support, etc.

It is highly recommended to learn the basics of HTML, CSS, and Javascript before learning Jquery.

Approach: You can insert a jQuery object before all paragraphs by using the method called .before().

  • before(): This method is used to insert content specified by the parameter, before each element in the set of matched elements. It can accept any number of additional argument like – .prepend() and .after().

  • isnertBefore(): It is similar to the above function but the content precedes the method and is inserted before the target, which in turn is passed as the .insertBefore() method’s argument.



Syntax:

$(target).before(contentToBeInserted).
$(contentToBeInserted).insertBefore(target).

Example:

HTML




<!DOCTYPE html>
<html>
    <head>
        <script src=
        </script>
        <meta charset="utf-8" />
        <meta name="viewport" 
              content="width=device-width" />
        <style type="text/css">
            button {
                display: block;
                margin: 20px 0 0 0;
            }
        </style>
    </head>
    <body>
      <h1 style="color: green;">
        GeeksforGeeks
    </h1>
    
    <h3>
        How to insert a jQuery object before
        all paragraphs using jQuery?
    </h3>
        <p>PHP Tutorial</p>
        <p>Python Tutorial</p>
        <p>Java Tutorial</p>
        <button id="button1">
          Click to see the effect
        </button>
        <script>
            $("#button1").click(function () {
                $("p").before("<i>GeeksForGeeks.com</i>");
            });
        </script>
    </body>
</html>

Output:

  • Before click: In the body element, we have initially 3 different paragraphs named – PHP tutorial, Python Tutorial, and Java Tutorial.

  • After click: After clicking the button, You can now notice that GeeksForGeeks.com is inserted before each paragraph.




My Personal Notes arrow_drop_up
Recommended Articles
Page :