Nuñito de la Calzada Nuñito de la Calzada - 6 months ago 8
Javascript Question

Jquery change the class of a whole li

I have this piece of code in my JSP:

<div class="thedescription">
<ul class="descriptionlanguages">
<li id="EN_langLinkLi" class="selectedlanguage" >
<a id="EN_langLink" class="showDifferentLang" href="#">EN</a>
</li>
<li id="IT_langLinkLi" class="notSelectedlanguage" >
<a id="IT_langLink" class="showDifferentLang" href="#">IT</a>
</li>
</ul>
</div>


and the script, that I use to change the class of the whole li

<script type="text/javascript">
$(document).ready(function(){
$('li').click(function() {
alert ('lsls');
$('#thedescription ul li ').each(function(){
this.className = 'notSelectedlanguage';
});
});
});
</script>


but does not change anything !

Answer

You can use addClass() to add class to clicked li and removeClass() to remove this class from siblings li

$('li').click(function() {
  $(this).addClass('notSelectedlanguage').siblings().removeClass('notSelectedlanguage');
});
.notSelectedlanguage {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="thedescription">
  <ul class="descriptionlanguages">
    <li id="EN_langLinkLi" class="selectedlanguage">
      <a id="EN_langLink" class="showDifferentLang" href="#">EN</a>
    </li>
    <li id="IT_langLinkLi" class="notSelectedlanguage">
      <a id="IT_langLink" class="showDifferentLang" href="#">IT</a>
    </li>
  </ul>
</div>

Comments