Narayana Vakkalagadda Narayana Vakkalagadda - 10 days ago 5
Javascript Question

removing class attribute from li on click

I have the following code in html. I just want to remove active class when we click on other li and add active class to li on which it is clicked.

<ul class="pagination" id="paginationUL">
<li class="active"><a href="#">1</a></li>
<li onclick="javascript:selectThis()"><a href="#">2</a></li>




I tried to remove the class first and it is not working. Please suggest.

function selectThis() {
$('ul[class="pagination"] li[class="active"]').removeClass("active"));
}


Edited the script and it is working.

Answer

You can write a line to bind to all li elements in that menu. The $(this) selector acts against the element clicked on, while using .siblings() acts on all other child li elements.

$('#paginationUL > li').click(function(){
  $(this).addClass('active').siblings().removeClass('active')
})
.active { background: orange; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="pagination" id="paginationUL">
    <li class="active"><a href="#">1</a></li>
    <li><a href="#">2</a></li>
    <li><a href="#">3</a></li>
 </ul>