简体   繁体   中英

jQuery if else unordered list addClass

I have a ul with four li elements. I want to check to see which one has the class .selected . If the li hasClass .selected , do nothing. If another .li in the same list does NOT have the .selected class, I want to add the class .li-border . In the code example below, I can get the console.log to fire but not the addClass. What am I missing? Thanks!

if ($("ul.portfolio-nav li a").hasClass("selected")) {
    console.log("yo");
} else {
    $(this).addClass("li-border");
};

Try this code :

 $("ul.portfolio-nav li a").each(function(){ if ( !$(this).hasClass("selected") ) { $(this).addClass("li-border"); }; }); 
 .li-border{ border: 1px solid black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class='portfolio-nav'> <li><a href='#'>First element</a></li> <li><a href='#' class="selected">Second and selected element</a></li> <li><a href='#'>Third element</a></li> </ul> 

Hope this helps.

The :not selector should do the trick:

$("ul.portfolio-nav li a:not(.selected)").addClass('li-border');

Or alternatively use the '.not' function, as suggested by jQuery documentation :

$("ul.portfolio-nav li a").not(".selected").addClass('li-border');

Don't over complicate yourself. Just remove all li-border class then add it to the one set you want to match too.

https://jsfiddle.net/da98dmgt/7/

$("ul.portfolio-nav li").click(function(){
    $("ul.portfolio-nav  ul li").removeClass("li-border");
    $(this).siblings("li").addClass("li-border");
});

Here's an example. It should be easy to replace the styles with the one you want.

 $(document).ready(function() { $("#list-items li").each(function() { if (!$(this).hasClass('selected')) { $(this).addClass('disable'); } }); }); 
 li:hover, .selected { text-decoration: underline; cursor: pointer; color: black; } .disable { color: gray; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <ul id="list-items"> <li>List item</li> <li>List item</li> <li class="selected">Selected item</li> <li>List item</li> </ul> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM