.hasClass()
Categories: CSS | Class Attribute | Attributes
.hasClass( className )Returns: Boolean
Description: Determine whether any of the matched elements are assigned the given class.
-
.hasClass( className )
version added: 1.0className The class name to search for.
Elements may have more than one class assigned to them. In HTML, this is represented by separating the class names with a space:
<div id="mydiv" class="foo bar"></div>
The .hasClass()
method will return true
if the class is assigned to an element, even if other classes also are. For example, given the HTML above, the following will return true
:
$('#mydiv').hasClass('foo')
As would:
$('#mydiv').hasClass('bar')
While this would return false
:
$('#mydiv').hasClass('quux')
-
Looks for the paragraph that contains 'selected' as a class.
HTML:
<p>This paragraph is black and is the first paragraph.</p> <p class="selected">This paragraph is red and is the second paragraph.</p> <div id="result1">First paragraph has selected class: </div> <div id="result2">Second paragraph has selected class: </div> <div id="result3">At least one paragraph has selected class: </div>
CSS:
p { margin: 8px; font-size:16px; } .selected { color:red; }
Code:
$("div#result1").append($("p:first").hasClass("selected").toString()); $("div#result2").append($("p:last").hasClass("selected").toString()); $("div#result3").append($("p").hasClass("selected").toString());
.hasClass( className )Returns: Boolean
Plugin: jQuery.fn.class
Description: Determine whether any of the matched elements are assigned the given class.
-
.hasClass( className )
version added: 1.0className The class name to search for or a regular expression.
The .hasClass()
method will return true if the class is assigned to an element or the regular expression test success, even if other classes also are.
-
Check if element has class foo.
HTML:
<div id="mydiv" class="foo bar"></div>
Code:
$('#mydiv').hasClass('foo')
Results:
true
-
Check if element has class fo.
HTML:
<div id="mydiv" class="foo bar"></div>
Code:
$('#mydiv').hasClass('fo')
Results:
false
-
Check if class of element match /fo\w+/.
HTML:
<div id="mydiv" class="foo bar"></div>
Code:
$('#mydiv').hasClass(/fo\w+/)
Results:
true