Bartosz
Bartosz

Reputation: 4602

Get html value from object within an array

I have an exemplary JavaScript code snippet. What I'm trying to achieve here is getting html, and id attribute value from an object within the array

var swatches = $(".swatchColor");
for (var i = 0; i < swatches.length; i++) {
     var value = parseInt(swatches[i].html());
     if (!isNaN(value)) {
         alert(swatches[i].attr("id"));
     }
};

but for some reason I get Uncaught TypeError: undefined is not a function error when swatches[i].html() is executed. Why does it happen?

Upvotes: 0

Views: 86

Answers (1)

Kodlee Yin
Kodlee Yin

Reputation: 1089

The jQuery class selector does not provide an array of node elements for you to iterate through.

From this answer, you need to do the following to iterate through all of the nodes:

$(".swatchColor").each(function(i, obj) {
    var value = parseInt($(obj).html());
    //etc...
});

Upvotes: 3

Related Questions