jQuery Selector How to - Add the previous selection to the current selection with andSelf








Question

We would like to know how to add the previous selection to the current selection with andSelf.

Answer


<!--   w ww .j a v a 2  s .  c  om-->
<html>
  <head>
    <script type="text/javascript" src='http://code.jquery.com/jquery-1.5.2.js'></script>
    <script type="text/javascript">
        $(document).ready(function(){
               $("div").find("p").andSelf().css("color","red");
        });
    </script>
    <style>
      .selected { color:blue; }
    </style>
  </head>
  <body>
          <div>
            <p>First Paragraph</p>
            <p>Second Paragraph</p>
          </div>
    </body>
</html>

The code above is rendered as follows: