jQuery Selector How to - Select if DIV has another tag








Question

We would like to know how to select if DIV has another tag.

Answer


<!-- w  w w .j  a v a 2 s  .  c  o  m-->
<html>
  <head>
    <style>
      .test{ border: 1px solid red; }
    </style>  
    <script type="text/javascript" src='http://code.jquery.com/jquery-1.5.2.js'></script>
    <script type="text/javascript">
    $(document).ready(function(){
         $("div:has(p)").addClass("test");
    });
    </script>
  </head>
  <body>
      <div><p>paragraph in div</p></div>
      <div>div</div>
  </body>
</html>

The code above is rendered as follows: