Reputation: 5031
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
Upvotes: 1
Views: 2844
Reputation: 17640
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 commented this could be shortend
var list = ["a1", "a2", "a3"];
$('#'+list.join(',#')).addClass('foo');
Upvotes: 1
Reputation: 49188
list = ["a1", "a2", "a3"];
$(list).each(function(){
$('#'+this).addClass('added');
});
EDIT
BoltClock's suggestion:
$.each(list, function(){
$('#'+this).addClass('added');
});
Upvotes: 4
Reputation: 7684
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';
}
}
Upvotes: 1
Reputation: 723498
Use .each()
and $.inArray()
:
var list = ['a1', 'a2', 'a3'];
$('div').each(function() {
if ($.inArray(this.id, list)) {
$(this).addClass('class');
}
});
Upvotes: 3