.hasClass()
In this chapter you will learn:
- Syntax and Description for .hasClass() method
- How to check if an element has a certain class
- Verify the existence of a class just added
- How to combine hasClass methods to filter
Syntax and Description
.hasClass(className)
determines whether any of the matched elements are assigned the given class.
className
is the class name to search for.
Its return value is a Boolean indicating whether the class is assigned to an element in the set.
<div id="mydiv" class="foo bar"></div>
Given the preceding HTML code, the following will return true:
$('#mydiv').hasClass('foo')
and
$('#mydiv').hasClass('bar')
Check if an element has a certain class
The following code selects an element by an id and then
checks to see if it has selected
class.
<html><!-- j a v a 2 s . c om-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert($("div#result1").hasClass("selected").toString());
});
</script>
<style>
.selected { color:red; }
.highlight { background:yellow; }
</style>
</head>
<body>
<body>
<p>A</p>
<p>B</p>
<p>C</p>
<div id="result1"></div>
</body>
</html>
Verify the existence of a class just added
The following code adds selected class to last
paragraph. After that it uses the hasClass
method to
check if the class has been added.
<html><!-- java2s. c om-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p:last").addClass("selected highlight");
alert($("p:last").hasClass("selected").toString());
});
</script>
<style>
.selected { color:red; }
.highlight { background:yellow; }
</style>
</head>
<body>
<body>
<p>A</p>
<p>B</p>
<p>C</p>
</body>
</html>
Combine hasClass methods
The following code uses filter methods and two .hasClass
methods. Each .hasClass
methods reference its own class name.
<html><!--from ja v a2 s .c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type='text/javascript'>
$(document).ready(
function() {
$('li')
.filter(
function() {
return $(this).hasClass('my2') || $(this).hasClass('my3');
}
)
.addClass('mySelected');
}
);
</script>
<style type='text/css'>
ul {
list-style: none;
margin: 5px;
padding: 0;
}
li.mySelected {
background: #a1e6b2;
border: 4px solid #93daa4;
}
</style>
</head>
<body>
<ul>
<li class='my3'>A</li>
<li class='my2'>B</li>
<li class='my3'>C</li>
<li class='my2'>D</li>
<li class='my'>E</li>
</ul>
</body>
</html>
Next chapter...
What you will learn in the next chapter:
- .height() (getter) Syntax and Description
- .height(value) (setter) Syntax and Description
- How to get the whole document height
- How to get the height for a tag
- How to set the height for a div element
- How to change the window height
- Use click event to trigger height method
- Chain height function with style setting