.insertBefore()

In this chapter you will learn:

  1. Syntax and Description for .insertBefore() method
  2. How to use .insertBefore to switch node sequence
  3. .insertBefore is the reverse of .before

Syntax and Description

.insertBefore(target)

inserts every element in the set of matched elements before the target. target is a selector, element, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s).

Return value is the jQuery object, for chaining purposes.

Consider the following HTML code:

<div class="container">
 <h2>Header</h2>
 <div class="inner">Hello</div>
 <div class="inner">InnerText</div>
</div>

When we apply the following code

$('<p>Test</p>').insertBefore('.inner');

The results would be:

<div class="container">/*  j  av a2s.  co m*/
 <h2>Header</h2>
 <p>Test</p>
 <div class="inner">Hello</div>
 <p>Test</p>
 <div class="inner">InnerText</div>
</div>

To select an element on the page and insert it before another we can use the following code.

$('h2').insertBefore($('.container'));

The results would be:

<h2>Header</h2>
<div class="container">
 <div class="inner">Hello</div>
 <div class="inner">InnerText</div>
</div>

Switch the node sequence

The following code inserts selected element before.

<html><!--from  j  av a  2s. c  o m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("p").insertBefore("#foo");

        });
    </script>
  </head>
  <body>
    <body>
         <p>a</p><div id="foo">java2s.com</div>

  </body>
</html>

Click to view the demo

.insertBefore is the reverse of .before

The reverse of $(A).before(B)

<html><!--  ja  v  a2s.co m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
          $("p").insertBefore( $("b") );
        });
    </script>
  </head>
  <body>
    <body>
         <b>java2s.com</b>
         <p>java2s.com:</p>
    </body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. Syntax and Description for .is()
  2. Check to see if the parent element is a form element
  3. Does the element have the style I need
  4. Switch with .is() method