Adding and Removing HTML Classes Upon Request With jQuery

Adding new HTML class is a no-brainer; just open the HTML document, locate what you want to add, insert and name the class. But when it comes to building an interactive website that allows your visitors to engage with it, you might need to modify, insert, and remove the HTML classes upon request.

You can do this with jQuery. This example function below will add and remove my-new-class to the <div>.

 // ## add class $('div').addClass('my-new-class'); // ## remove class $('div').removeClass('my-new-class'); 

We can also use standard JavaScript code to add/remove HTML classes like so:

 // add class document.getElementById('elem').className = 'my-new-class'; // remove class document.getElementById('elem').className = document.getElementByTag('div').className.replace( /(?:^|\s)my-new-class(?!\S)/g , '' ) 

The code as you can see above is less straightforward than when we are doing it with a JavaScript Framework jQuery. But if you don’t want to rely on a framework, you can always use a new JavaScript API called classList.

Using classList API

Similar to jQuery, classList provides a set of methods that allow us to modify HTML classes.

In a case where there is a div with multiple classes, we can retrieve the classes that are assigned in the div using classList.

 var classes = document.getElementByID('elem').classList; console.log(classes); 

When we open the browser Console, we can see the list of the classes.

To add and remove class, we can use .add() and .remove().

 var elem = document.getElementByID('elem'); // add class elem.classList.add('my-new-class'); // remove class elem.classList.remove('my-new-class'); 

Adding multiple classes can also be done by separating each class with a comma:

 elem.classList.add('my-new-class', 'my-other-class'); 

To check whether certain elements contain the specified class, we can use .contains(). It will return true if the class specified is present, and return false if it does not.

 elem.classList.contains('class-name'); 

We can also toggle the class using .toggle(). The following code snippet shows how we bind the .toggle()method with a mouse click event.

 var button = document.getElementById('button'); function toggle() { elem.classList.toggle('bg'); } button.addEventListener('click', toggle, false); 

Check out the demo in action from the following links.

Final Thought

classList is a new native JavaScript API that is also introduced along with HTML5. It is neat and simple, and works in the following browsers: Firefox 3.6, Opera 11.5, and Chrome 8, and Safari 5.1. It is however absent in Internet Explorer 9 and below, so you may have to use the Polyfills when implementing classList API in Internet Explorer.

Further Resource


    



via hongkiat.com http://rss.feedsportal.com/c/35261/f/656072/s/36040589/sc/4/l/0L0Shongkiat0N0Cblog0Chtml50Edatalist0Eapi0C/story01.htm