Is it possible to select only direct descendants of an element using jQuery's find()
or children()
functions?
I have several ul
elements, each with other ul
elements inside them, and some root li
elements too. I store a specific parent ul
in a variable (as a jQuery object) and then look for any of the root li
elements within using: my_root_ul.find('li');
.
However, this method also finds any li
that belongs to the ul
inside the ul
, if that makes sense.
My question is, how can I select only direct descendants of type li
within the my_root_ul
object using find()
. Ordinarily, we could use something like $('ul > li')
to return only direct li
elements, but it must be possible to filter down the returned elements?
Here is an example to demonstrate what I mean:
<ul> <li>I want this <ul> <li>I don't want this</li> <li>I don't want this</li> <li>I don't want this</li> </ul> </li> <li>I want this</li> <li>I want this</li> </ul>
The jQuery find() method is used to get the descendant elements of the selected element. The find() and children() methods are similar, except that the find() method search through multiple levels down the DOM tree to the last descendant, whereas the children() method only search a single level down the DOM tree.
jQuery find() Method The find() method returns descendant elements of the selected element, all the way down to the last descendant.
The ("parent > child") selector selects all elements that are a direct child of the specified element.
find() can traverse down multiple levels to select descendant elements (grandchildren, etc.)
Like this:
my_root_ul.find('> li');
.children()
also selects only the immediate children, so you can use that also:
my_root_ul.children('li');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With