Search code examples
javascriptjqueryparent-childparent

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><a href="#">I want the span</a></li>
</ul>


Solution

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

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

    http://jsfiddle.net/dyev5/