Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over jQuery $(this).attr('class').split(" ") gives odd results

I've got a page where I'm trying to fetch arrays of classes for lots of divs which share a common class. For example:

<div class="common lorem ipsum"></div>
<div class="common dolor sit"></div>
<div class="common hello world"></div>

I want to fetch each common class div and get an Array of it's classes. At the moment, I'm doing it by using this bit of jQuery:

$('.common').each(function(index) {
  var classes = $(this).attr('class').split(" ");
  for(var i in classes) {
    alert(classes[i]);
  }
});

Looking at the first resulting classes variable gives this:

classes: Array (3)
0: "common"
1: "lorem"
2: "ipsum"
length: 3
__proto__: Array

The problem is that the for(var i in classes) seems to be iterating over the __proto__ Array and delving down into that as well - has anybody ever come across this before? I'm using the latest version of Chrome (6.0.453.1).

like image 361
Sam Starling Avatar asked Jul 05 '10 17:07

Sam Starling


2 Answers

for ( var i = 0, l = classes.length; i<l; ++i ) {
 alert( classes[i] );
}

Iterate through an array with a regular for loop, not a for...in otherwise it enumerates through the array's properties ( since its still an object and has other properties in addition to the elements inside ).

like image 98
meder omuraliev Avatar answered Nov 15 '22 19:11

meder omuraliev


To add to the other valid answers, since you're already using jQuery, you can take advantage of jQuery.each:

$.each(classes, function (i, cls) {
    alert(cls);
});
like image 28
Ates Goral Avatar answered Nov 15 '22 19:11

Ates Goral