.hasClass()

jQuery

.hasClass()


.hasClass( className ) Returns: Boolean

Description: Determine whether any of the matched elements are assigned the given class.

  • version added: 1.2.hasClass( className )

    • className
      Type: String
      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:

1
                                
<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:

1
                                
$('#mydiv').hasClass('foo')

As would:

1
                                
$('#mydiv').hasClass('bar')

While this would return false:

1
                                
$('#mydiv').hasClass('quux')

Example:

Looks for the paragraph that contains 'selected' as a class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
                                  
<!DOCTYPE html>
<html>
<head>
<style>
p { margin: 8px; font-size:16px; }
.selected { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<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>
<script>
$("div#result1").append($("p:first").hasClass("selected").toString());
$("div#result2").append($("p:last").hasClass("selected").toString());
$("div#result3").append($("p").hasClass("selected").toString());
</script>
</body>
</html>