Check an element hasClass with vanilla Javascript

Check an element hasClass with vanilla Javascript

Consider two DOM elements below:

Element example 1
Element example 2

To check which element has class "test", we should create a helper function and use it like this:

function hasClass(elementId, className) {
	const element = document.getElementById(elementId);
	return (` ${element.className} `).replace(/[\n\t]/g, ' ').indexOf(` ${className} `) > -1;

console.log(hasClass('el1', 'test')) // true
console.log(hasClass('el2', 'test')) // false

The function need two parameters: elementId is ID of element that you want to find class name className

The replace method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced
The indexOf method returns the first index at which a given element can be found in the array, or -1 if it is not present

© 2019 4codev

Created with love by Sil.