最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use jquery to change the class of a target element from array - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Jan 19, 2013 at 17:25 RobRob 11.5k10 gold badges40 silver badges56 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

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 {

    }
}
发布评论

评论列表(0)

  1. 暂无评论