Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery hasClass when the selector is a JS variable

I am trying to use jQuery's hasClass function. It doesn't seem to work when I use it like this. I would appreciate it if anyone can work out how to use hasClass in this situation.

The error I am getting is

numValueElement.hasClass is not a function
if($(numValueElement.hasClass("tag"))) 

The key line throwing this error is this one if($(numValueElement.hasClass("tag")))

$(".numberValue").click
    (
        function ()
        {
            var numValueElement = this;
            var propertyId = numValueElement.id;
            $(".numberBounds").filter("#"+propertyId).toggle();
            if($(numValueElement.hasClass("tag")))
            {
            }

        }
    );
like image 915
Ankur Avatar asked Jun 25 '11 14:06

Ankur


People also ask

How do you check if an element has a specific class in jQuery?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

How do I test whether an element has a particular class?

To check if an element contains a class, you use the contains() method of the classList property of the element:*

How check class is active or not in jQuery?

The jQuery hasClass() method is used to check whether selected elements have specified class name or not. It returns TRUE if the specified class is present in any of the selected elements otherwise it returns FALSE. Syntax: $(selector).

How do you target a class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.


2 Answers

.hasClass() is a jQuery object method, not something attached to the element itself.

You need to know the difference between a jQuery object wrapped element, and a plain DOM element.

What you want is:

$(numValueElement).hasClass("class-name")
like image 103
Orbling Avatar answered Oct 07 '22 04:10

Orbling


Like this:

if( $(yourVariable).hasClass("someClass") ) {

}
like image 35
Ken D Avatar answered Oct 07 '22 06:10

Ken D