Skip to content

Instantly share code, notes, and snippets.

@janbiasi
Created July 1, 2014 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janbiasi/168d34e12ceb00f9abf1 to your computer and use it in GitHub Desktop.
Save janbiasi/168d34e12ceb00f9abf1 to your computer and use it in GitHub Desktop.
Working with HTML classes like jQuery's addClass and removeClass
function isElement(obj) {
try {
// For Firefox, Opera and Chrome
return obj instanceof HTMLElement;
}
catch(e){
// IE Bugfix
return (typeof obj==="object") &&
(obj.nodeType===1) && (typeof obj.style === "object") &&
(typeof obj.ownerDocument ==="object");
}
}
// Get classes from a DOM Element
function getClasses(elem) {
if(isElement(elem)) {
return elem.className.split(/\s+/)
}
return null;
}
// Check the classes of a DOM Element
function hasClass(elem, clazz) {
if(isElement(elem)) {
var _classes = getClasses(elem);
for(var i = 0; i < _classes.length; i++) {
if(_classes[i] == clazz) return true
}
return false
}
return null;
}
var myElement = document.getElementById('myElement'); // #myElement.testClass
var myClasses = getClasses(myElement); // [testClass]
if(hasClass(myElement, "testClass") { // true
alert("My element has the class 'testClass'!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment