jQuery .prepend() inserts content at the beginning of each element in the matched elements.

Syntax and Description

.prepend method inserts content at the beginning of each element in the matched elements.

  • .prepend(content)
    content: An element, an HTML string, or a jQuery object to insert at the beginning of each element in the set of matched elements
  • .prepend(function)
    function: A function that returns an HTML string to insert at the beginning of each element in the set of matched elements

Its return value is the jQuery object, for chaining purposes.

Add text node

The following code adds data to each tag with prepend.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from   ww w . ja  va2s .c  om-->
             $("*", document.body).each(function () {
                  $(this).prepend(document.createTextNode("data"));

             });
        });
    </script>
    <style>
      .y { background:yellow; }
  </style>

  </head>
  <body>
    <body>
       <div><button disabled="disabled">First</button> 
            <span class="selected">java2s.com</span>
            <span></span>
       </div>

  </body>
</html>

Click to view the demo

Insert to a span element

The following code inserts content to the inside of every matched element.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from w  ww.j a v a2s .c  o m-->
             $("span").prepend("<b>Hello </b>");
        });
    </script>
  </head>
  <body>
    <body>
        <span>span</span>
        <div id="foo">FOO! java2s.com</div>
  </body>
</html>

Click to view the demo

Insert a selected element

The following code inserts a selected element b.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from  w  w  w. j  ava2  s  . c om-->
               $("p").prepend( $("b") );
        });
    </script>
  </head>
  <body>
    <body>
         <p> a</p><b>java2s.com</b>
  </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities