user664546
user664546

Reputation: 5031

add class to div if id is equal to value from a list

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

Answers (4)

mcgrailm
mcgrailm

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

Jared Farrish
Jared Farrish

Reputation: 49188

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

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

http://jsfiddle.net/qgeVH/2/

EDIT

BoltClock's suggestion:

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

http://jsfiddle.net/qgeVH/4/

Upvotes: 4

Shaokan
Shaokan

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

http://jsfiddle.net/qgeVH/3/

Upvotes: 1

BoltClock
BoltClock

Reputation: 723498

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

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

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

Upvotes: 3

Related Questions