开发者

How to wrap span around ul li but not in Child ul?

How can I affect the ul.menu li a elements only, and not child elements (ul.submenu li a)?

Here is my code:

$('ul.menu li a').wrap('<span></span>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="menu">
  <li><a href="#">I want the span</a></li>
  <li><a href="#">I want the span</a>
    <ul class="submenu">
      <li><a href="#">Don't want the span</a></li>
      <li><a href="#">Don't want the span</a></li>
      <li><a href="#">Don't want the span</a></li>
    </ul>
  </li>
  <li><a href="#">I want the span</a></li>
  <li&开发者_Go百科gt;<a href="#">I want the span</a></li>
</ul>


You should use the child selector rather than just the descendant selector:

$('ul.menu > li > a').wrap('<span></span>');

http://jsfiddle.net/dyev5/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜