Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Direct descendants only with jQuery's find()

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> 
like image 809
BenM Avatar asked Dec 07 '11 12:12

BenM


People also ask

How to find descendant in jQuery?

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.

Which jQuery method returns descendant elements of the selected element all the way down to the last descendant?

jQuery find() Method The find() method returns descendant elements of the selected element, all the way down to the last descendant.

What will select all direct child elements in jQuery?

The ("parent > child") selector selects all elements that are a direct child of the specified element.

Which of the following function can traverse down multiple levels to select descendant elements?

find() can traverse down multiple levels to select descendant elements (grandchildren, etc.)


1 Answers

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'); 
like image 54
Tatu Ulmanen Avatar answered Oct 02 '22 20:10

Tatu Ulmanen