I have this string of numbers var array = 1,6,2,9,5
which is retrieved from an API so I can really change the way it is.
and I have this in my html:
<div class="1 btn">Foo 1</div>
<div class="2 btn">Foo 2</div>
<div class="3 btn">Foo 3</div>
<div class="4 btn">Foo 4</div>
<div class="5 btn">Foo 5</div>
<div class="6 btn">Foo 6</div>
<div class="7 btn">Foo 7</div>
<div class="8 btn">Foo 8</div>
<div class="9 btn">Foo 9</div>
I want to add on any class that exists into the array a class 'foo
'. So in my example div's 1,6,2,9,5 will get a class 'foo
'.
How can I achieve that?
6 Answers 6
A quick way:
$('.' + array.join(', .')).addClass('foo');
edit — if the "array" is actually a string:
$('.' + array.split(',').join(', .')).addClass('foo');
3 Comments
You can take advantage of the fact that jQuery will allow you multiple selectors separated by commas, which is pretty close to what you already have:
If array
is really an array:
$("." + array.join(", .")).addClass("foo");
If it's a string (e.g. "1,2,3"
) instead:
$("." + array.replace(/,/g, ", .")).addClass("foo");
2 Comments
replace
does not replace all occurrences unless you feed it a regex as the first parameter). Edited the answer to fix.Try this:
for (var i=0; i<array.length; i++)
{
$('.' + array[i]).addClass('foo');
}
Comments
Using ES5 .some
: http://jsfiddle.net/rkknp/1/.
var array = [1, 6, 2, 9, 5];
// filter elements that have a class apparent in the array
$(".btn").filter(function() {
return array.some( $.fn.hasClass.bind( $(this) ) );
}).addClass("red");
Comments
You are using invalid names for your CSS classes.
The name can contain characters a-z, A-Z, digits 0-9, period, hyphen, escaped characters, Unicode characters 161-255, as well as any Unicode character as a numeric code, however, they cannot start with a dash or a digit.
See http://www.w3.org/TR/CSS2/syndata.html#characters, Which characters are valid in CSS class names/selectors? and Allowed characters for CSS identifiers.
Comments
This should work. Note that I'm using jQuery in this code
var yourArray = [1,6,2,9,5];
var elements = $('div');
for(var i=0; i<yourArray.length; i++){
$(elements[yourArray[i]-1]).addClass('foo');
}
1,6,2,9,5
a string?[1, 6, 2, 9, 5]
. People do themselves no favors with broken sample code in their questions.