jQuery
var myID = new Array("A1","B2");
$.each($(".tab"), function(index,value) {
var id = value.attr('id'); //error here :(
if(id == myID[index])
id.addClass('sel');
}
HTML
<div class="tab" id="A1"></div>
<div class="tab" id="A2"></div>
<div class="tab" id="A3"></div>
<div class="tab" id="B1"></div>
<div class="tab" id="B2"></div>
<div class="tab" id="B3"></div>
What I am trying to achieve here is, I want to add class to html which have matched with array myID. The code I have above throws an error on the line var id = value.attr('id');.
Can anyone help me fix this?
You can use $.fn.each instead of $.each – either one will let you refer to the DOM element with the
thiskeyword or the second argument (value)Alternatively, you can iterate over your array and add the class directly: