McDan Garrett
McDan Garrett

Reputation: 183

.addClass not working

I am trying to add a class to a div using .addClass()

Here is how I am trying to do it:

<script>
$("#circle").hover(function() {
    ("#circle").addClass("new_style");
});
</script>

and I have this div

<div id="circle" class="lol"></div>

Upon inspecting the element and and viewing the console I can see the error

"Uncaught TypeError: Object #circle has no method 'addClass' "

Upvotes: 2

Views: 7863

Answers (1)

Matt Ball
Matt Ball

Reputation: 360066

You missed a $ before ("#circle"):

$("#circle").hover(function() {
    $("#circle").addClass("new_style");
});

However, you don't need to re-query the DOM for that element at all!

$("#circle").hover(function() {
    $(this).addClass("new_style");
});

And even then, you don't need to re-jQuery-ify that object. Reuse the jQuery object for less of a performance hit:

var $circle = $("#circle");

$circle.hover(function() {
    $circle.addClass("new_style");
});

Interestingly, neither JSLint nor JSHint caught this sloppy error.

Upvotes: 7

Related Questions