Gleiemeister 2000
Gleiemeister 2000

Reputation: 729

Uncaught TypeError: Object #<HTMLDivElement> has no method 'attr'

Im trying to grab my divs with the class tooltip.

And then do something like this:

var schemes = $(".tooltip");

for (var i in schemes) {
    var scheme = schemes[i];
    console.log(scheme.attr("cost"));
}

But it throws the above error. What am i missing? (Im new to javascript + jquery obviously)

Upvotes: 18

Views: 27185

Answers (2)

VisioN
VisioN

Reputation: 145408

If you use for-loop to iterate jQuery set, you should get the elements with eq() method, but not using square bracket notation (i.e. []). The code like $(".tooltip")[i] will pick up DOM elements, but not jQuery objects.

var schemes = $(".tooltip");
for (var i = 0; i < schemes.length; i++) {
    var scheme = schemes.eq(i);
    console.log(scheme.attr("cost"));
}

However, you may always use each() to iterate jQuery set:

$(".tooltip").each(function() {
    var scheme = $(this);
    console.log(scheme.attr("cost"));
});

Upvotes: 33

adeneo
adeneo

Reputation: 318252

var schemes = $(".tooltip");

schemes.each(function(index, elem) {
    console.log($(elem).attr('cost'));
});

As a sidenote "cost" is not a valid attribute for any element as far as I know, and you should probably be using data attributes.

Upvotes: 4

Related Questions