简体   繁体   中英

Use jquery to change the class of a target element from array

I have a List li of elements that I used .toArray() . I now need to loop through them to find the desired element and change its style Class.

I am not sure what I am doing wrong, but I cannot seem to get the class of the index item, but I can retrieve the innerHTML no problem.

var viewsIndex = $('#viewsList li').toArray()
        for(i=0; i < viewsIndex.length; i++) {
            if(viewsIndex[i].innerHTML == selectedTab) {

                console.log(viewsIndex[i].attr('style')); //This does NOT work
                console.log(viewsIndex[i].innerHTML); //This does work
            }
            else
            {


            }
        }

Once I target the Element, I want to use .removeClass and .addClass to change the style.

This is the DOM object which doesn't have jQuery functions:

viewsIndex[i]

This is the jQuery object which has the attr function:

$(viewsIndex[i]).attr('style')

Anyway, your code could be a lot simpler with this:

$('#viewsList li').filter(function(){
    return this.innerHTML == selectedTab;
}).removeClass('foo').addClass('bar');

You are trying to call jQuery function on DOM object convert it to jQuery object first.

Change

viewsIndex[i].attr('style')

To

$(viewsIndex[i]).attr('style')

couldn't you use .each() ?

$('#viewLists li').each(function(i){
    if($(this).html == selectedTab){
       $(this).removeClass('foo').addClass('bar');
    }
});

Loop over the elements using jQuery each and then access them as $(this) . This way you'll have access to jQuery methods on each item.

$('#viewsList li').each(function(){

    var element = $(this);

    if(element.html() == selectedTab){
        console.log(element.attr('style')
    } else {

    }
}

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