使用jQuery选择*don't*包含链接

Use jQuery to select list items that *don't* contain a link

本文关键字:包含 链接 jQuery 选择 don 使用      更新时间:2023-09-26

尝试为ul中不包含链接的所有元素添加背景色

HTML:

  <ul id="list">
    <li><a href="http://google.com/">Google</a></li>
    <li><a href="http://yahoo.com/">Yahoo</a></li>
    <li>Not a link</li>
    <li><a href="http://live.com/">Live</a></li>
    <li>Not a link</li>
  </ul>

Javascript:

  $('#list li').css({'background': 'red'});

但这改变了他们所有人——http://jsbin.com/pusogihuvi/1/edit?html,js,输出

使用:not伪选择器排除匹配项。使用:has伪选择器查看元素是否包含指定的匹配项(不丢失祖先作用域)。

$('#list li:not(:has(a))').css({'background': 'red'});

您可以组合:not:has:

$('#list > li:not(:has(a))').css({'background': 'red'});

http://jsbin.com/quyalunipo/1/edit?html,css,js,输出