0

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?

Bartosz
  • 4,542
  • 11
  • 43
  • 69

1 Answers1

3

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...
});
Community
  • 1
  • 1
Kodlee Yin
  • 1,089
  • 5
  • 10
  • That eventually worked for me, but had to change it to: var value = parseInt($(obj).html()); Please consider updating your answer, will mark it as an answer – Bartosz Jun 24 '14 at 16:06
  • `obj` is a DOM element, not a jQuery object. Your answer has the same problem as the original question. – Andrew Whitaker Jun 24 '14 at 16:16