1

I have an Array- myArray which is filled with objects obtained while looping using ".each"

Now I want to add a class .active

the array object can be printed using alert and shows correct innerhtml.

but how do i add class to the object?

Code:-

var myArray=new Array();

I tried this:-

$(myArray[1]).addClass('active');
1
  • 4
    Please share the .each loop as well Commented Jun 23, 2011 at 9:35

3 Answers 3

3

Try mapping through your array:

$.map(myArray, function(elem) {
    $(elem).addClass('active');
});

Edit: A not so misleading way (thx @Sébastien RoccaSerra):

$.each(myArray, function(i,elem) {
    $(elem).addClass('active');
});
Sign up to request clarification or add additional context in comments.

6 Comments

Your exemple works, but can be misleading. The 'map' function is more often used to produce a new array than to exert side effects on items. The 'each' function is more appropriate to iterate a function across an array. Just replacing 'map' with 'each' in your example looks more intention revealing to me. Cheers!
@Sébastien RoccaSerra I agree.
@inti of course it does. Use ES5 shim to support legacy browsers. Array.prototype.map is part of the standard.
@SebastienRoccaSerra apart from that $.each supplies the key as the first parameter and the value as the second
@Raynos $(myArray.map(function(v) { return v; })) equals $(myArray) so why use map here, or am I missing something?
|
1

try:

myArray[1].addClass('active'); 

or

myArray.eq(1).addClass('active');

Comments

0
$(myArray)[1].addClass('active');

3 Comments

$(myArray)[1] is a DOM element and has no function addClass or am I wrong?
Correct me if I'm wrong, but if 'myArray' contains DOM elements, '$(myArray)' would be a collection of jQuery objects, which you can iterate with '.each()' and referencing to with '$(myArray)[x]', from what I know.
You are right. Not my day today. $(myArray)[1][0] would be the DOM element of the 2nd entry in $(myArray).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.