Reputation: 4172
Why do I can't get required result from this code:
element.children().find('ul').first();
It returns prevObject.
When I use:
element.children('ul')
It works well. I dont understand what the difference is.
My html is like this:
<div>
<ul>
<li>adssfsdf</li>
<li>dfdfghdfh</li>
</ul>
</div>
You can see that problem at jsfiddle .
Upvotes: 2
Views: 814
Reputation: 90
element.children().find('ul').first()
as per your html
element.children() return the ul element
element.children().find('ul') return nothing as you are finding the ul inside ul element
Because of this your css is not applying.
Upvotes: 0
Reputation: 10683
Check the children and find functions clearly here. i have mentioned the comments as well.
<div>
<ul>
<li>adssfsdf</li>
<li>dfdfghdfh</li>
</ul>
</div>
$('div').children('ul').css({'color':'red'}); // children ul inside div
$('div').children('ul:first').css({'color':'red'}); // first ul inside div
$('div').find('ul').css({'color':'blue'}); // ul inside div
$('div').children('ul').find('li:first').css({'color':'green'}); // first li of ul inside div
check her also: https://jsfiddle.net/aezyjgtt/2/
Upvotes: 0
Reputation: 198436
find
searches for descendants that match the selector. children
searches for children that match the selector. Say you have this tree:
A -> B -> C -> D
Then,
$(".A").children() // B
$(".A").find() // B, C, D
$(".A").children().find() // C, D
Why does the last one find only C
and D
? Because it searches the descendants of the children.
In your case - you first get the children, then search for the descendants of those children that are ul
. But the children have no descendants, and you get no results. When you do .children('ul')
, you are looking for children who are ul
- and there is indeed one such.
Upvotes: 1
Reputation: 25892
From the jquery docs
.find( selector )
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
So element.find('ul')
gets all the ul
children of element
If you want to get ul
using find
you should say
element.find('ul').first();
Upvotes: 0