-1

I would like to add a class "my-class-to-add" for each "FIRST" element inside this class "menu-item-has-children" that has "ul" on it.

I tried it using this one but only the second menu the class was added. Thanks for your help.

   <script>
            jQuery(document).ready(function ($) {
                $('.nav-menu .menu-item-has-children ul:eq(1)').each(function() {
                        $(this).addClass('my-class-to-add');
                });
          });
  </script>
sbgib
  • 5,580
  • 3
  • 19
  • 26
  • 1
    Please post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Jun 14 '21 at 07:46
  • https://api.jquery.com/first-child-selector/ – freedomn-m Jun 14 '21 at 08:03
  • Does this answer your question? [How to select first child with jQuery?](https://stackoverflow.com/questions/5852452/how-to-select-first-child-with-jquery) – freedomn-m Jun 14 '21 at 08:05

1 Answers1

0

Not seeing your HTML makes this harder, but perhaps

$(function() {
  $('.nav-menu .menu-item-has-children').each(function() {
    $('ul:eq(0)',this).addClass('my-class-to-add');
  })
});
.my-class-to-add {
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nav-menu">
  <div class="menu-item-has-children">
    <ul>
      <li>First</li>
    </ul>
    <ul>
      <li>second</li>
    </ul>
  </div>
  <div class="menu-item-has-children">
    <ul>
      <li>First</li>
    </ul>
    <ul>
      <li>second</li>
    </ul>
  </div>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236