Ads 468x60px

Labels

Wednesday, May 2, 2012

Parent/child relation selectors

jQuery also allows you to select elements based on their parent element. There are two variations: One which will only match elements which are a direct child to the parent element, and one which will match all the way down through the hierarchy, e.g. a child of a child of a child of a parent element. The syntax for finding children which are direct descendants of an element looks like this:
$("div > a")
This selector will find all links which are the direct child of a div element. Replacing the greater-than symbol with a simple space will change this to match all links within a div element, no matter if they are directly related or not:
$("div a")
Here's an example where we color bold tags blue if they are directly descending from the first test area:
Bold text Italic text
Bold text 2 Italic text 2
Bold text 3
As you will see, only the first bold tag is colored. Now, if you had used the second approach, both bold tags would have been colored blue. Try the following example, where the only thing changed is the greater-than character which has been replaced with a space, to note that we also accept non-direct descendants or "grand children" as they are sometimes called:
Bold text Italic text
Bold text 2 Italic text 2
Bold text 3
Now the cool thing is that you can actually go back up the hierarchy if needed, using the parent() method. We'll look into that in another chapter of this tutorial.

0 comments:

Post a Comment

 

Sample text

Sample Text

Sample Text