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?

3
  • 1
    Try $(swatches[i]).html(). As noted below though, .each() is the more common way of accomplishing this. Commented Jun 24, 2014 at 15:59
  • 1
    If you're using jQuery, you should consider using its each method. Commented Jun 24, 2014 at 15:59
  • That was the answer. Thanks very much Commented Jun 24, 2014 at 16:00

1 Answer 1

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...
});
Sign up to request clarification or add additional context in comments.

2 Comments

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
obj is a DOM element, not a jQuery object. Your answer has the same problem as the original question.

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.