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/
精彩评论