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

javascript - jquery .css.attr.addClass not working on span tag - Stack Overflow

programmeradmin2浏览0评论

I'm trying to set the background colour of a span using jquery. I've used all functions in the title and all give me an error:

SCRIPT438: Object doesn't support property or method 'css'/'attr'/'addClass'

Any idea how I can solve this? All I want is to change the bg colour however I prefer if I can set the class.

code:

var liList = ul.find('li span');
        $.each(liList, function(index, value){
            if(value.innerText == currPage){
                value.css('background-color', '#D94A38');
            }
        });

I'm trying to set the background colour of a span using jquery. I've used all functions in the title and all give me an error:

SCRIPT438: Object doesn't support property or method 'css'/'attr'/'addClass'

Any idea how I can solve this? All I want is to change the bg colour however I prefer if I can set the class.

code:

var liList = ul.find('li span');
        $.each(liList, function(index, value){
            if(value.innerText == currPage){
                value.css('background-color', '#D94A38');
            }
        });
Share Improve this question edited Jan 14, 2013 at 12:14 Jonny asked Jan 14, 2013 at 12:11 JonnyJonny 2,92710 gold badges43 silver badges66 bronze badges 3
  • 1 As Aleksandr said, you need to show your code. We can't see what is wrong until we have something to work with! – AlienHoboken Commented Jan 14, 2013 at 12:13
  • @jerome.s yes I'm using it in the same function which works perfectly – Jonny Commented Jan 14, 2013 at 12:13
  • 1 Watch out for innerText usage on the DOM element as that may not be supported on all browsers. You can use $(value).text() as an alternative. – diffa Commented Jan 14, 2013 at 12:24
Add a ment  | 

3 Answers 3

Reset to default 7

The each() function gives you DOM object not jQuery object

Change to

$(value).css('background-color', '#D94A38');

Your code would be

var liList = ul.find('li span');
    $.each(liList, function(index, value){
        if(value.innerText == currPage){
            $(value).css('background-color', '#D94A38');
        }
});

value is not a jQuery object (it's a DOM object).

This:

value.css('background-color', '#D94A38');

Should be:

$(value).css('background-color', '#D94A38');

Check out the .each() docs for additional information.

i think if you replace value by $(value) your problem will solved

发布评论

评论列表(0)

  1. 暂无评论