admin管理员组文章数量:1390444
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 04 Answers
Reset to default 4list = ["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');
本文标签: javascriptadd class to div if id is equal to value from a listStack Overflow
版权声明:本文标题:javascript - add class to div if id is equal to value from a list - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744604711a2615281.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论