开发者

Target an empty <li>

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


Use the :empty psuedo-selector.

$('li:empty').addClass('empty')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜