jQuery Selector How to - Find the parent element of each paragraph with a class "selected"








Question

We would like to know how to find the parent element of each paragraph with a class "selected".

Answer


<!--  w  ww . j  a v a2s.c  o m-->
<html>
  <head>
    <script type="text/javascript" src='http://code.jquery.com/jquery-1.5.2.js'></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("p").parent(".selected").css("background", "yellow");
        });
    </script>
  </head>
  <body>
          <div><p>Hello</p></div>
          <div class="selected"><p>Hello Again</p></div>
  </body>
</html>

The code above is rendered as follows: