Reputation: 10283
I know this one must be a simple one for the jQuery gurus here, but I honestly have no idea how to accomplish it.
I have the following HTML:
<div class="panel_contents">
<ul>
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
<li></li>
<li></li>
</ul>
</div>
I need to target the empty <li>
and attach a class to them, for example class="empty". I don't want to modify the HTML to manually add the classes for presentational purposes if I don't have to.
I started a JSFIDDLE here for demo purposes.
Thanks a million for any help with this.
--
EDIT 3 [9/16/14]
Today, I admit that maybe using jQuery might not be really necessary since empty elements can be targeted with CSS using the :empty
pseudo-selector, which is actually quite well supported across all browsers all the way down to IE8 (albeit partial support) - http://caniuse.com/#search=empty
EDIT 2
Here's Another Solution.
This solution looks for <a href>s
inside the <li>
, if it has one, it will NOT add the class, if there are no <a href>s
, then the class empty is added.
EDIT 1
Thanks to Daniel for the solution. Here's a WORKING DEMO
Upvotes: 0
Views: 3510
Reputation: 190915
Use the :empty
psuedo-selector.
$('li:empty').addClass('empty')
Upvotes: 12