PROWAREtech
JavaScript: Determine If an Element Has a Class
Determine if an HTML element has a class assigned to it.
This super simple function determines if an HTML element is using a particular class.
function hasClass(element, className) {
if (element.classList) {
return element.classList.contains(className);
} else {
return new RegExp("(^| )" + className + "( |$)", "gi").test(element.className);
}
}
Example usage:
<html>
<head><title></title>
<script type="text/javascript">
function hasClass(element, className) {
if (element.classList) {
return element.classList.contains(className);
} else {
return new RegExp("(^| )" + className + "( |$)", "gi").test(element.className);
}
}
window.onload = function () {
if (hasClass(document.getElementById("div"), "bottom")) {
alert("has the class 'bottom'");
}
};
</script>
</head>
<body>
<div id="div" class="abs right bottom float"></div>
</body>
</html>
Comment