1

I am trying to construct a jquery statement that will slideUp() all <ul> elements whose siblings don't contain a set of specific classes (.clicked, .chosen).

Suppose I have the following nested <ul> structure:

<ul class="mainmenu">
    <li>Dogs</li>
    <ul>
        <li>Fido</li>
        <li class="chosen">Barney</li>
        <li>Turbo</li>
    </ul>
    <li>Cats</li>
    <ul>
        <li>Sylvester</li>
        <li>Felix</li>
        <li>Garfield</li>
    </ul>
    <li class="clicked">Hamsters</li>
    <ul>
        <li>Chubbs</li>
        <li>Oreo</li>
        <li>Ruby</li>
    </ul>
</ul>

For the above example, I would like to slideUp() only the 'Cats' <ul> element ('Sylvester', 'Felix', 'Garfield') because none of it's elements use the 'chosen' or 'clicked' classes.

My current jquery statement reads:

$('.mainmenu').first().siblings().not('.clicked, .chosen').slideUp();

This, and everything else I have tried, returns nothing. Suggestions?

2
  • 2
    As a note, as this is also going to affect the selectors in JavaScript: The way you nest the uls is invalid. A nested ul should be a child of an li and not a sibling of it. Sep 22, 2016 at 6:51
  • @mrtedweb check my answer to achieve the same. Sep 22, 2016 at 7:33

1 Answer 1

0

You HTML looks challenging :) but somehow, I've managed to create a query to perform what you're looking for.

And if you want to check multiple class for particular element you can use is() as well.

//Check li doesn't have clicked class and then filter ul next to the li 
$('.mainmenu > li').not('.clicked').next('ul').filter(function(){
  //Find the ul, if it's any of li doesn't have chosen class 
  if(!$(this).find('li').hasClass('chosen'))
  {
    return $(this);
  }
}).slideUp();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="mainmenu">
    <li>Dogs</li>
    <ul>
        <li>Fido</li>
        <li class="chosen">Barney</li>
        <li>Turbo</li>
    </ul>
    <li>Cats</li>
    <ul>
        <li>Sylvester</li>
        <li>Felix</li>
        <li>Garfield</li>
    </ul>
    <li class="clicked">Hamsters</li>
    <ul>
        <li>Chubbs</li>
        <li>Oreo</li>
        <li>Ruby</li>
    </ul>
</ul>

1
  • Guess the quote is misplaced. It has to be $('.mainmenu').find('li:eq(1)').slideUp(); :-)
    – David R
    Sep 22, 2016 at 6:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.