Narayana Vakkalagadda
Narayana Vakkalagadda

Reputation: 15

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.

Upvotes: 0

Views: 1498

Answers (5)

BenM
BenM

Reputation: 53246

Your selectors are incorrect. You need to use the ID (#) or class (.) selector:

$('#paginationUL li.active').removeClass("active");

However, you're better off not using intrusive event handlers, and rather doing something along the lines of the following:

$('#paginationUL > li').on('click', function() {  
    $(this).addClass('active').siblings('.active').removeClass('active');
});

The latter example will apply a class of active to the clicked element and remove it from any other elements in the <ul>.

Upvotes: 2

jmcgriz
jmcgriz

Reputation: 3353

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>

Upvotes: 0

Your selector is incorrect. Use #paginationUL[class="pagination"] li[class="active"] or ul.pagination li.active or #paginationUL li.active

Upvotes: 1

brunouno
brunouno

Reputation: 595

If you're using jquery this should do it:

$('#paginationUL li').click(function(){
    $('#paginationUL li').removeClass("active");
    $(this).addClass('active');
});

Upvotes: 1

Ajaykumar
Ajaykumar

Reputation: 416

You can use something like this

$("#paginationUL li").click(function() {
    $(this).toggleClass("active");
    $(this).siblings().removeClass("active");
});

Upvotes: 1

Related Questions