jQuery – Descendants And Children
The distinction between the child of a particular element and a descendant of an element isn’t unique to jQuery. The same concepts are used in CSS too. For those who are new to this, and as a recap for all the experts out there, here is the definition for each:
- Descendant – any element that exists within another element.
- Child – a direct descendant.
Here is some code to illustrate:
<div>
<p>
<span>Here is some text</span>
</p>
</div>
The <span> is a child of the <p> and a descendant of the <div>. The <p> is a child of the <div>. Children are direct descendants (i.e. they’re still descendants), so the <p> is also a descendant of the <div>.
Phew. Anyway, now that we’ve got that out of the way, let’s explore how jQuery enables us to select children and descendants of particular elements.
Selecting Descendants In jQuery
In jQuery, we have the powerful find() function. Find() selects all descendants of an element. Consider the following code:
<div>
<p>
<span>Here is some text</span>
<span>Here is some more text</span>
</p>
</div>
To select both spans, we can use
jQuery('div').find('span')
Selecting Children In jQuery
There are two ways we can select children in jQuery: using CSS notation (ul > li), or using the children() function. To select only the<p> in the <div>, you can use
jQuery('div > p')
or
jQuery('div').children()
The only problem with the second method is that all children are selected. That’s OK in our simple example, but if you add a second <div> within the first, that will get selected too. In this case, if you wanted to select only the children of the outer <div> that were <p>s, you could filter the children() function like this:
jQuery('div').children('p')
Intuitive, or what!