-->

28 April 2021

jQuery ancestor descendant Selector

  Asp.Net CS By Example       28 April 2021
jQuery to Select Direct Descendants

 In this post, we are learning about jQuery to Select Direct Descendants. To select all <p> elements in a page that have <div> elements as ancestors, we can use this selector:

 $('div p') 

 Note that this code selects all <p> elements that are descended from <div> elements. So this code matches this.

 <div>
  <p>This is paragraph 1.</p>   
 </div> 

 And it also matches this.

 <div>
 <span>
 <p>This is paragraph 1.</p>
 </span>
</div> 

 If we want to select only the first type of <p> elements those with direct parent </div> elements we can use this selector.

 $('div > p') 


 Below code example puts for see above jQuery to Select Direct Descendants selector working.

jqscript.html
<html>
<head>
 <title>
   Selecting direct
   descendants
 </title>
 <script src="http://code.jquery.com/jquery-latest.js"></script>
 <script type="text/javascript">
  function setStyle() {
    $('div > p').css("font-style", "italic");
  }
 </script>
</head>
<body>
 <h1>Selecting direct descendants</h1>
 <div>
  <span>
   <p>This is paragraph 1.</p>
  </span>
  <p>This is paragraph 2.</p>
  <p>This is paragraph 3.</p>
  <p>This is paragraph 4.</p>
 </div>
 <p>This is paragraph 5.</p>
 <form>
  <input type="button"
    value="Select"
    onclick="setStyle()"
  </input>
 </form>
</body>
</html>


Output:

logoblog

Thanks for reading jQuery ancestor descendant Selector

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.