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

javascript - add class to div if id is equal to value from a list - Stack Overflow

programmeradmin2浏览0评论

Hi i need to add a class to a div if its id is equal to a value from list:

list = ["a1", "a2", "a3"]

<div id="a1"></div>
<div id="b1"></div>
<div id="c1"></div>
<div id="a3"></div>

any help is appreciated

thanks J

Hi i need to add a class to a div if its id is equal to a value from list:

list = ["a1", "a2", "a3"]

<div id="a1"></div>
<div id="b1"></div>
<div id="c1"></div>
<div id="a3"></div>

any help is appreciated

thanks J

Share Improve this question edited Apr 16, 2011 at 22:46 Jared Farrish 49.3k17 gold badges99 silver badges107 bronze badges asked Apr 16, 2011 at 22:41 user664546user664546 5,0514 gold badges24 silver badges19 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 4
list = ["a1", "a2", "a3"];

$(list).each(function(){
    $('#'+this).addClass('added');
});

http://jsfiddle/qgeVH/2/

EDIT

BoltClock's suggestion:

$.each(list, function(){
    $('#'+this).addClass('added');
});

http://jsfiddle/qgeVH/4/

Use .each() and $.inArray():

var list = ['a1', 'a2', 'a3'];

$('div').each(function() {
    if ($.inArray(this.id, list)) {
        $(this).addClass('class');
    }
});

The first thing came to my mind is that you can create a for loop:

for(var i = 0; i < list.length; i++){
     if(document.getElementById(list[i])) {
       document.getElementById(list[i]).className = 'added2';
     }
}

http://jsfiddle/qgeVH/3/

here is an alternative JSFIDDLE DEMO you can turn the list into a string delimited by ",#" to create a selector

var list = ["a1", "a2", "a3"];

var joined_list = list.join(',#'); //turn into string
// you need to add a "#" to the beginning of the string to make a proper selector
$('#'+joined_list).addClass('foo');

as mented this could be shortend

 var list = ["a1", "a2", "a3"];
 $('#'+list.join(',#')).addClass('foo');
发布评论

评论列表(0)

  1. 暂无评论