Technotip IT Solutions
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:
$("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
xHTML code
Descendant Selectors
Technotip IT Solutions
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
$(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:
$("div div")
To select a p tag inside a div which is inturn inside another div, we write:
$("div div p")
We could even combine the id, class names and the tag names while selecting the elements.
class name: para
$("div div p.para")
ID name: para
$("div div p#para")
Optimization Tip:
Being as specific as possible helps speedup the process of selecting the element.