Selecting elements that are descendants of another element

In this post of JQuery, I will show how to select elements that are descendants of another element.

Below is the complete html code that will be used as an example


1  <html>
2   <head>
3       https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
4   </head>
5   <body>
6       
7           function selectDescendantElement() {
8               var $element = $('div li');
9               alert($element.length);
10          }
11      
12      <input id="Items1Button" name="Items1" type="button" value="Items1" onclick="selectDescendantElement();"/>
13      
14
    15
  • Item1
  • 16
  • Item2
  • 17
  • Item3
  • 18
19
20
21 Paragraph content 22
23 </body> 24 </html>

The jQuery syntax will be

$(parentSelector tagName)

where
parentSelector –> Selector identifying the parent element
tagName –> tagName of the childrens

In our example I have created one javascript functions “selectDescendantElement”.

selectDescendantElement will select all the elements that are descendants (indirect children) of element Items1, which is list containing 3 items. Refer to line 8.

Leave a Reply