Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove class using index

This might be easy but I am having trouble in getting it to work. I am using .each() to iterate through a list. I was wondering if it is possible to remove a class using the index.

eg. If there were 10 items in the list and I want to remove the class from the 5th element when I click the 8th element for example.

$(function () {
var items = $('#v-nav>ul>li').each(function (index) {
    $(this).click(function () {
        if (index = 8)
{
$(#5).removeClass('class');
}
    });
});

Anyone with any ideas? Thank you

like image 939
everreadyeddy Avatar asked Mar 19 '26 21:03

everreadyeddy


2 Answers

Change

$(#5).removeClass('class');

To

$('#v-nav>ul>li:eq(4)').removeClass('class');

Its better to assign the element returned by your selector to do the same processing again to get desired element.

$(function () {
    var items = $('#v-nav>ul>li')

       $('#v-nav>ul>li').click(function () {
          if ($(this).index() = 8)
          {
             $(items).eq(4).removeClass('class');
          }
       });
});
like image 52
Adil Avatar answered Mar 22 '26 09:03

Adil


There's no need to iterate with each(), as each element already has an index, and using eq() will let you select elements based on the index they have in the DOM. This solution is dependant on the elements being siblings() etc.

$(function () {
    var elems = $('#v-nav>ul>li');

    elems.on('click', function() {
        if ($(this).index()==8) elems.eq(4).removeClass('class');
    });
});

You could also just bind the click to that one element:

$(function () {
    $('#v-nav>ul>li:eq(7)').on('click', function() {
         $(this).siblings().filter(':eq(4)').removeClass('class');
    });
});

Otherwise I would just do:

$(function () {
    var elems = $('#v-nav>ul>li');
    $.each(elems, function(idx, elm) {
        if (idx==8) elems.eq(4).removeClass('class');
    });
});

As a sidenote ID's consisting of just a number (or starting with a number) is invalid.

like image 43
adeneo Avatar answered Mar 22 '26 11:03

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!