Descendant Selectors: jQuery

Video tutorial illustrating the syntax of Descendant selectors.

For the purpose of demonstration, we are using simple html structure. It may not suit the requirement of a descendant selector, but we’re using it to keep things simple and easy to understand the syntax of descendant selectors.

In a complex xHTML or XML structure we could have multiple p tags nested inside a div tag and you want one of these p tags to work on. In such a complex case, you are better to go with descendant selectors.

You could select it as follows:

1
 $("div p:first")

Here it selects the first p tag present inside the div.

jQuery uses simple verbs like first, append, remove etc: which we’ll cover in upcoming tutorials.

Video Tutorial: Descendant Selectors: jQuery


[youtube https://www.youtube.com/watch?v=t044xeB1wKQ]

YouTube Link: https://www.youtube.com/watch?v=t044xeB1wKQ [Watch the Video In Full Screen.]



xHTML code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
 <head><title>Descendant Selectors</title>
 
 <link rel="stylesheet" href="style.css" type="text/css" />
 
 </head>
 <body>
 
   <div id="main">
 
    <div>
 
     <p>Technotip IT Solutions</p>
 
    </div>
 
   </div>
 
   <button id="main_div">Main Div</button>
   <button id="sub_div">Sub Div</button>
   <button id="sub_div_para">Sub Div Paragraph</button>
 
 
   <script type="text/javascript" src="script/jquery-1.8.1.min.js"></script>
   <script type="text/javascript" src="script/my_script.js"></script>
 </body>
</html>

In the xHTML file, observe the nesting of elements / tags. And the id’s given to div and the buttons.

jQuery Code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready( function() {
 
 $("#main_div").click( function() {
   $("#main").css("background-color", "black");
  });
 
  $("#sub_div").click( function() {
   $("div div").css("background-color", "yellow");
  });
 
    $("#sub_div_para").click( function() {
   $("div div p").css("color", "orange");
  });
 
});

To know about .css method of jQuery watch: Animation of Text and Image: jQuery

Observe the descendant selectors in above code.

To select a div inside another div, we write:

1
$("div div")

To select a p tag inside a div which is inturn inside another div, we write:

1
$("div div p")

We could even combine the id, class names and the tag names while selecting the elements.
class name: para

1
$("div div p.para")

ID name: para

1
$("div div p#para")

Optimization Tip:
Being as specific as possible helps speedup the process of selecting the element.