.andSelf()

In this chapter you will learn:

  1. Syntax and Description for .andSelf() DOM method
  2. How to reference current and next element
  3. How to add tag back and move on

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><!--from  ja v  a2 s .  co  m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
             $("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><!--from  j a  va2s  .  c  o m-->
<html>
    <head>
        <script src='http://java2s.com/style/jquery-1.8.0.min.js'>
        </script>
        <script >
            $(function(){
                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

Next chapter...

What you will learn in the next chapter:

  1. Syntax and Description for .append() method
  2. How to append hard code HTML tags
  3. How to add text node created by document
  4. How to add element to all paragraphs