How do I apply a JQuery function to elements with the same class that have a specific number of children?

StackOverflow https://stackoverflow.com/questions/18730326

  •  28-06-2022
  •  | 
  •  

Question

I am working on a navigation menu that has several ul elements with their respective children or li's. I would like to change the class name only on the ul element that has a specific number of children. I have tried the following but it applies the function to all ul elements regardless of how many children it contains.

if( $('ul.menu_container > li').length >= 3 ){
  $('ul.menu_container').attr('class','mynewclass');}};

This is the HTML part:

<ul class="menu_container">
  <li>menu item 1</li>
  <li>menu item 2</li>
  <li>menu item 3</li>
  <li>menu item 4</li>
</ul>
<ul class="menu_container">
  <li>menu item 1</li>
</ul>
<ul class="menu_container">
  <li>menu item 1</li>
</ul>

Hopefully I was clear enough on my question and what I'm trying to accomplish. Thanks in advance for any help I may get.

Était-ce utile?

La solution

You need to iterate through all of the ul try this

$('.menu_container').each(function(){
    if( $(this).find('li').length >= 3 ){
        $(this).addClass('mynewclass');
    }
});

FIDDLE

Autres conseils

Well just glancing at your code I see the if the condition is met then the class "mynewclass" will be applied to EVERY element with ul.menu_container. For you code to work you would need to formate it like this:

if( $('ul.menu_container > li').length >= 3 ){
    $(this).attr('class','mynewclass');}

But I am fairly certain that this will not work either because it will only evaluate the first matching set. You will need to write your code using a .each() function.

You can always just add an additional class to the first group of menu items and use that new class as the selector:

    <ul class="menu_container NEW_CLASS_NAME">
        <li>menu item 1</li>
        <li>menu item 2</li>
        <li>menu item 3</li>
        <li>menu item 4</li>
    </ul>
    ...

Then add the new class with the following code:

    $('.NEW_CLASS_NAME').addClass("mynewclass");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top