tags:

views:

51

answers:

3

hi guys,

i wonder how i can query if a ul has a first-child li with a certain classname?

like…

<ul>
<li>list element 1</li>
<li>list element 2</li>
</ul>

<ul>
<li class="whatever">list element 1</li>
<li>list element 2</li>
</ul>

i want to query if ul has a child with classname whatever -> do something! is that even possible?

thank you

A: 
$('ul').find('.whatever').length > 0

if so you have some, not else

helle
+3  A: 

Combine the :has() and > (immediate child) selectors, like this:

$('ul:has( > li.whatever)')​

You can view a demo here, this matches only if an immediate child <li> has class="whatever", without the >, it would match if any descendant had that class.

Alternatively, go the other way:

$("li.whatever").parent("ul")

This would find all the immediate .parent() of elements with that class only if they're a <ul> (as opposed to a <ol>).


I think you meant an immediate child, but in case you need to match only when the first <li> that's an immediate child has the class, add the :first-child selector, like this:

$('ul:has( > li.whatever:first-child)')

You can see a test page here

Nick Craver
You still need to add `:first` or `:first-child` (I think): *if a ul has a **first-child** li with a certain classname*
Felix Kling
@Felix Kling: I *think* he means immediate child, which is often the case with `<ul>`/`<li>`, but I'll update in case that's the situation.
Nick Craver
A: 

If I didn't get it wrong:

$(function(){
    $("ul li.whatever:first-child").css({border: "1px solid red"});
});
Álvaro G. Vicario