How to select a specific ul with jquery

Asked

Viewed 98 times

0

    $('.menu-expand').click(function () {
       $(this).find('ul').toggleClass("menu-mobile-expandido");
    });

I would select not any ul, but the first ul within the class .menu-expand.

I tried to use .menu-expand > ul inside the find but it didn’t work.

  • $(this).find('ul:first') does not solve the problem? or simply $('ul.menu-expand:first')

3 answers

1

You can use the method first() of Jquery where this will return the first element of the collection.

$('.menu-expand').click(function() {
    $(this).find('ul').first().toggleClass("menu-mobile-expandido");
});

See documentation: first()

0

Exists in css selector o :first-child

You could use it like this:

$('.menu-expand').click(function () {
   $('.menu-expand ul:first-child').toggleClass("menu-mobile-expandido");
});

The idea to select the first child ul inside the . menu-expand

0

A very practical way to do this is by using the selector :eq(), with it you do not get stuck to the first element, can put any number there, leaving the code much more flexible, even to be used with a for for example.

$('.menu-expand').on('click', function () {
   $('.menu-expand:eq(0)').css('color','red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul >
  <li class="menu-expand">UM</li>
  <li class="menu-expand">DOIS</li>
  <li class="menu-expand">TRÊS</li>
</ul>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.