jQuery .andSelf() DOM method

Syntax and Description

.andSelf()

adds the previous selection to the current selection.

The return value is the new jQuery object.

Select Current and next

The following code combines current selected and next elements and apply styles.


<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 .ja  va2 s .com-->
             $("div.selected").next().andSelf().css("background", "yellow");
        });
    </script>
  </head>
  <body>
    <body>
          <div>java2s.com</div>
          <div>java2s.com</div>
          <div>java2s.com</div>
          <div class="selected">java2s.com</div>
          <div>java2s.com</div>
  </body>
</html>

Click to view the demo

Add tag back

The following code uses .andSelf() to add a div back onto the stack after doing a .find() manipulates the stack.


<!DOCTYPE html>
<html>
    <head>
        <script src='http://java2s.com/style/jquery-1.8.0.min.js'>
        </script>
        <script >
            $(function(){<!--from ww w  . java  2 s  .c o  m-->
                document.writeln( $("div") );
                document.writeln( $( "div" ).find("p") );
                document.writeln( $( "div" ).find("p").andSelf() );
            });
        </script>
    </head>
    <body>
        <div>
            <p>Paragraph</p>
            <p>ja va2s.com</p>
            <p>Paragraph</p>
        </div>
    </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities