PROWAREtech

articles » current » javascript » determine-if-an-element-has-a-class

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>

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT