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');