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><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>');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.