Selecting elements that are direct children of another element

In this post of JQuery, I will show how to select elements that are direct childrens 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 selectElementByHierarchy1() {
8               var $element = $('#Items1 > li');
9               alert($element.length);
10          }
11          
12          function selectElementByHierarchy2() {
13              var $element = $('#Items2 > li');
14              alert($element.length);
15          }
16      
17      <input id="Items1Button" name="Items1" type="button" value="Items1" onclick="selectElementByHierarchy1();"/>
18      <h1>Items1</h1>
19      <ul id="Items1">
20          <li>Item1</li>
21          <li>Item2</li>
22          <li>Item3</li>
23      </ul>
24      <input id="Items2Button" name="Items2" type="button" value="Items2" onclick="selectElementByHierarchy2();"/>
25      <h1>Items2</h1>
26      <ul id="Items2">
27          <li>Item1</li>
28          <li>Item2</li>
29          <li>Item3</li>
30          <li>Item4</li>
31      </ul>
32  </body>
33 </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 two javascript functions “selectElementByHierarchy1” and “selectElementByHierarchy2”

selectElementByHierarchy1 will select all the elements that are children of element Items1. Refer to line 8.

selectElementByHierarchy2 will select all the elements that are children of element Items2. Refer to line 13.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s