Reputation: 15
First off, forgive me if this is a redundant question. I think you'll agree that it's a difficult case to reasonably specifically search for.
I have html that looks like
<li class='signature'>
<span class='label'>Signature:</span>
<div class='folding'>
<span class='data'></span>
</div>
</li>
<li class='issuer'>
<span class='label'>Issuer:</span>
<span class='data'></span>
</li>
etc etc.
I want to use jquery to do an .addClass only to any li that contains a div of the class "folding", but not to the other lis. I'm sure that I can do this using a cunningly-crafted .each statement, but I kind of feel intuitively that there must be a way to do this using just jquery selectors. I have gotten as far as
$('li > .moreclick').addClass("arrowable");
but that of course adds the class to the span, and not to the li.
Am I stuck with an .each? (and if so, any hints on the best way to do that would be nice, but admittedly outside the scope of the question).
Thanks!
Upvotes: 1
Views: 137
Reputation: 327
Please try this:
$("li:has(div.folding)").addClass("new-class")
This will selects exactly the li
element which is the parent of divs
that have class 'folding'
.
Upvotes: 0
Reputation: 2942
If you want to check only the direct children of li:
$('li:has(> div.folding)').addClass("arrowable");
Upvotes: 0
Reputation: 30135
for example:
$('.folding').parent().addClass('arrowable');
//edit too slow..
Upvotes: 0
Reputation: 1233
If the li
is always going to be the absolute parent:
$("div.folding").parent().addClass("new-class")
Otherwise, this will keep searching up the hierarchy until it finds an li
:
$("div.folding").closest("li").addClass("new-class")
[edit] dioslaska's solution is much nicer. Keeping mine here for reference though.
Upvotes: 2
Reputation: 3350
Try the following
$('li:has(.folding)').addClass("arrowable");
Upvotes: 2