tadam logo
Did you find an error in the text?
Select this with mouse and press
Ctrl + Enter
Xhtml.co.il Check Spelling
Orphus system

hasClass()

.hasClass( className )

Returns: Boolean

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

.hasClass( className )

version added: 1.2
className
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')

Examples

Looks for the class 'selected' on the matched elements.
$("div#result1").append($("p:first").hasClass("selected").toString());
$("div#result2").append($("p:last").hasClass("selected").toString());
$("div#result3").append($("p").hasClass("selected").toString());
The output of the code above will be:
Full source:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
$("div#result1").append($("p:first").hasClass("selected").toString());
$("div#result2").append($("p:last").hasClass("selected").toString());
$("div#result3").append($("p").hasClass("selected").toString());
  });
  </script>
  <style>
  p { margin: 8px; font-size:16px; }
  .selected { color:red; }
  .highlight { background:yellow; }
  </style>
</head>
<body>
  <p>Hello</p>
  <p class="selected">Goodbye</p>
  <div id="result1">First paragraph has selected class: </div>
  <div id="result2">Last paragraph has selected class: </div>
  <div id="result3">Some paragraph has selected class: </div>
</body>
</html>
Was this information helpful?
   

Comments