"The class attribute is mostly used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML DOM) to make changes to HTML elements with a specified class." --W3
To Change/Replace CSS Class with Javascript (cross-browser):
To replace all existing classes with one or more new classes, set the 'className' attribute by fetching element in DOM using
getElementById or
getElementsByClassName or
getElementsByTagName...
document.getElementById("IDofElement").className = "MyClass";
//For Multiple Classes, use a space-delimited list
//e.g. "MyClass MyClass1 MyClass2"
Add an Additional Class to an element using Javascript:
To add a class or more than one class to an element, without affecting/replacing/removing existing classes/values, append a space in start and the new classname, like:
document.getElementById("IDofElement").className += " MyClass";
//For Multiple Classes, use a space-delimited list
//e.g. " MyClass MyClass1 MyClass2"
Remove a Class with Javascript:
To remove a(single) class with javascript to an element without altering any other classes (in case there are more than one.):
document.getElementById("IDofElement").className = document.getElementById("IDofElement").className.replace( /(?:^|\s)MyClass(?!\S)/g , '' )
//Regex Explanation
//(?:^|\s) -- checks and match the start of the string, or single whitespace character
//MyClass -- the literal(name) text for the class to remove
//(?!\S) -- lookahead to verify the above is the whole classname, ensures end of string or a space.
Check if a Class is already applied:
if ( document.getElementById("IDofElement").className.match(/(?:^|\s)MyClass(?!\S)/) )
//For Regex Explanation look previous code
Assigning above actions to an event:
function modifyClass(){
document.getElementById("IDofElement").className = "MyClass";
//or any other code example from above
}
window.onload = function(){
document.getElementById("IDofElement").addEventListener( 'click' , modifyClass );
//in this case addEventListener is listening to click event
//but we can use any event depending on our use
}
To ADD Class with jQuery:
$('#IDofElement').addClass('MyClass');
Remove a Class with Javascript:
$('#IDofElement').removeClass('MyClass');
Check if a Class is already applied:
if ( $('#IDofElement').hasClass('MyClass') ){
//any code here
};
Toggle/Swap between two Classes:
$('#IDofElement').toggleClass('MyClass');
Assigning above actions to an event:
$('#IDofElement').click(changeClass);
No comments :
Post a Comment
Dare to Ask?