Selecting Child Elements Only - J Query

Problem
You need to select one or more direct children of a particular element.

Solution

Use the direct descendant combinator (>). This combinator expects two selector expressions,one on either side. For example, if you want to select all anchor elements that reside directly beneath list items, you could use this selector: li > a. This would select all anchors that are children of a list item; in other words, all anchors that exist directly beneath list items. Here’s an example:

Now, to select only the anchors within each list item, you would call jQuery like so:

The third anchor within the #nav list is not selected because it’s not a child of a list item;
it’s a child of a <span>element.

Discussion
It’s important to distinguish between a child and a descendant. A descendant is any element existing within another element, whereas a child is a direct descendant; the analogy of children and parents helps massively since the DOM’s hierarchy is largely similar to that.
It’s worth noting that combinators like >can be used without an expression on the left side if a context is already specified:

Selecting children in a more programmatic environment should be done using jQuery’s children() method, to which you can pass a selector to filter the returned elements.This would select all direct children of the #content element:

The preceding code is essentially the same as jQuery('#content > *') with one important difference; it’s faster. Instead of parsing your selector, jQuery knows what you want immediately. The fact that it’s faster is not a useful differential, though. Plus, in some situations, the speed difference is marginal verging on irrelevant, depending on the browser and what you’re trying to select. Using the children() method is especially useful when you’re dealing with jQuery objects stored under variables. For example:

In fact, there are even more ways of achieving it! In this situation, the first method is the fastest. As stated earlier, you can pass a selector expression to the children() method to filter the results:

Only paragraph elements that are direct children of #content will be returned.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics