Skip to content

Instantly share code, notes, and snippets.

@bergantine
Last active February 9, 2021 04:20
Show Gist options
  • Save bergantine/1165817 to your computer and use it in GitHub Desktop.
Save bergantine/1165817 to your computer and use it in GitHub Desktop.
JavaScript hasClass(), addClass(), removeClass(). #javascript
// class manipulation from http://www.openjs.com/scripts/dom/class_manipulation.php
function hasClass(ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
@tbleckert
Copy link

Old one but just stumbled across this one and I notice that you have this.hasClass in the addClass function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment