简体   繁体   中英

Javascript - add class to element, remove from siblings

Code is very basic (you can get the idea when you look at it, no need to explain), somehow it doesn't work... can anyone please tell me what am i doing wrong?

 $("ul li").click(function() { $(this).addClass('cell-selected') .parent().siblings().find('.cell-selected').removeClass('cell-selected'); }); 
 .cell-selected { color: #fff; background: #5b2200; border-color: #ce5209; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <ul> <li class="cell-selected"><a>First</a></li> <li><a>Second</a></li> <li><a>Third</a></li> </ul> 

fiddle

$("ul li").click(function() {

  $(this).addClass('cell-selected')
      .siblings().removeClass('cell-selected')
});

You are looking siblings of selected li .So,no need of parent() and find('.cell-selected').

You can try with it:

 $("ul li").click(function() {
        $(this).addClass('cell-selected').siblings().removeClass('cell-selected');
 });

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