Created
July 1, 2014 07:20
-
-
Save janbiasi/168d34e12ceb00f9abf1 to your computer and use it in GitHub Desktop.
Working with HTML classes like jQuery's addClass and removeClass
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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