.andSelf()

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(){<!--  ww w.j ava2s .c  om-->
             $("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

The code above generates the following result.

.andSelf()

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(){<!--  ww  w.j a v  a 2  s.  com-->
                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

The code above generates the following result.

.andSelf()
Home »
  Javascript Tutorial »
    jQuery Reference »
      DOM
...
$("html tags")
.add()
.addClass()
.after()
.andSelf()
.append()
.appendTo()
.attr()
.before()
.children()
.clone()
.closest()
.contents()
.css()
.detach()
.filter()
.first()
.get()
.has()
.hasClass()
.height()
.html()
.index()
.innerHeight()
.innerWidth()
.insertAfter()
.insertBefore()
.is()
.last()
.map()
.next()
.nextAll()
.nextUntil()
.not()
.offset()
.offsetParent()
.outerHeight()
.outerWidth()
...