jQuery : 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:

<div id="divTestArea1">        <b>Bold text</b>        <i>Italic text</i>        <div id="divTestArea2">                <b>Bold text 2</b>                <i>Italic text 2</i>                <div>                        <b>Bold text 3</b>                </div>        </div></div><script type="text/javascript">
$("#divTestArea1 > b").css("color", "blue");</script>
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:

<div id="divTestArea1">        <b>Bold text</b>        <i>Italic text</i>        <div id="divTestArea2">                <b>Bold text 2</b>                <i>Italic text 2</i>                <div>                        <b>Bold text 3</b>                </div>        </div></div><script type="text/javascript">
$("#divTestArea1 b").css("color", "blue");</script>
Now the cool thing is that you can actually go back up the hierarchy if needed, using the parent() method.









SHARE
    Blogger Comment
    Facebook Comment