2

I have:

    $('#a1').addClass('play');
    $('#a3').addClass('play');
    $('#a5').addClass('play');  
    $('#a16').addClass('play');
    $('#b3').addClass('play');

So decided it was best to use something like:

var doString="m7,m7,a1,b2,c3,p16,o15,n14,d8,e7,g5,i4,l4,n6,o8,n10,m11,k12,i11,i13,k15,l16,f9";
var strArray1 = doString.split(",");
console.log(doString);
console.log(strArray1);

$.each(strArray1, function(i, elem) { 
    console.log(elem); 
    $('#'+elem+').addClass('play'); // not working
});

But can't figure the correct parameter to add the class to each element.

How can I do this?

1
  • sorry, I edited out my original question, as I was trying to solve it myself and copied another non working copy. Realised my mistake and edited, still that one wasn't working. Thanks for your help. Commented Aug 16, 2012 at 18:25

1 Answer 1

4
$.each(strArray1, function(i, val) { 

    // i => index(0,1,..)
    // val => m7,m7,a1,...

    $( '#' + val ).addClass('play'); 
});

OR

$.each(strArray1, function() { 

    // this[0] => m7,m7,a1,...

    $( '#' + this[0] ).addClass('play'); 
});

After edit (your code)

$.each(strArray1, function(i, elem) { 
    console.log(elem); 
    $('#'+elem+').addClass('play'); // not working
});

Where $('#'+elem+') should be $('#'+ elem ).

Here, you've to remove the trailing +' from the selector and then its perfect.

Sign up to request clarification or add additional context in comments.

2 Comments

a simple for loop would reduce the overhead of the call to $.each
@MrOBrian may be, but this help OP to find the error and correct path.

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.