Add or Remove a CSS Class with Vanilla JavaScript

View: 553    Dowload: 0   Comment: 0   Post by: hanhga   Category: Javascript   Fields: Other

9 point/1 review File has been tested

Sometimes you need to add or remove a CSS class with JavaScript, and you don’t want to include an entire library like jQuery to do it.

This is useful in situations when you want your page elements to change in response to user actions.

Example uses include:

  • Showing or hiding a menu
  • Highlighting a form error
  • Showing a dialog box
  • Showing different content in response to a selection
  • Animating an element in response to a click

There are two JavaScript properties that let you work with classes: className and classList. The former is widely compatible, while the latter is more modern and convenient. If you don’t need to support IE 8 and 9, you can skipclassName.

We’ll start with the compatible version first.

Modifying Classes the Compatible Way

The JavaScript className property lets you access the class attribute of an HTML element. Some string manipulation will let us add and remove classes.

We’ll access HTML elements using querySelectorAll(), which is compatible with browsers from IE8 and up.

Add a Class

To add a class, we’ll write a function that takes in the elements we want to change and adds a specified class to all of them.

function addClass(elements, myClass) {

  // if we have a selector, get the chosen elements
  if (typeof(elements) === 'string') {
    elements = document.querySelectorAll(elements);
  }

  // if we have only one dom element, make it an array to simplify behavior
  else if (!elements.length) { elements=[elements]; }

  // add class to all chosen elements
  for (var i=0; i<elements.length; i++) {
    if (!(' '+elements[i].className+' ').indexOf(' '+myClass+' ') > -1) {
      elements[i].className += ' ' + myClass;
    }
  }
}

You’ll see how the function works soon, but to watch the function in action, feel free to use this CSS:

.red{
  background: red;
}

.highlight{
  background: gold;
}

…and this HTML:

<div id="iddiv" class="highlight">ID div</div>

<div class="classdiv">Class div</div>
<div class="classdiv">Class div</div>
<div class="classdiv">Class div</div>

Here are some usage examples of the function itself:

addClass('#iddiv','highlight');
addClass('.classdiv','highlight');

addClass(document.getElementById('iddiv'),'highlight');
addClass(document.querySelector('.classdiv'),'highlight');
addClass(document.querySelectorAll('.classdiv'),'highlight');

Notice that you can identify the HTML elements you want to change through a selector or you can directly pass in the elements themselves.

How Our addClass Function Works

Our addClass function first takes two parameters: the HTML elements we want to modify and the class we want to add. Our goal is to loop through each HTML element, make sure the class is not already there, and then add the class.

First, if we’ve chosen to identify our HTML elements through a selector such as #iddiv or .classdiv, then we can usequerySelectorAll() to grab all of our desired elements.

// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
  elements = document.querySelectorAll(elements);
}

However, if DOM elements are fed into the function directly, we can loop through them. If there’s only one element, we’ll make it an array so we can use the same loop and simplify our code.

// if we have only one DOM element, make it an array to simplify behavior
else if (!elements.length) { elements=[elements]; }

Now that we have our elements in a format we can loop over, we’ll go through each one, check if the class is already there, and if not, we’ll add the class.

// add class to all chosen elements
for (var i=0; i<elements.length; i++) {
  if (!(' '+elements[i].className+' ').indexOf(' '+myClass+' ') > -1) {
    elements[i].className += ' ' + myClass;
  }
}

Notice we’re adding a space at the beginning and end in order to simplify the pattern we’re looking for and avoid needing a regular expression.

In any case, we’re done — you can now add a class!

Remove a Class

To remove a class, we can use the following function:

function removeClass(elements, myClass){

  // if we have a selector, get the chosen elements
  if (typeof(elements) === 'string') {
    elements = document.querySelectorAll(elements);
  }

  // if we have only one dom element, make it an array to simplify behavior
  else if (!elements.length) { elements=[elements]; }

  // create pattern to find class name
  var reg = new RegExp('(^| )'+myClass+'($| )','g');

  // remove class from all chosen elements
  for (var i=0; i<elements.length; i++) {
    elements[i].className = elements[i].className.replace(reg,' ');
  }
}

Most of this removeClass function works the same way as our addClass function; by gathering the desired HTML elements and looping through them. The only difference is the part where the class gets removed.

Here’s the class removal in more detail:

// create pattern to find class name
var reg = new RegExp('(^| )'+myClass+'($| )','g');

// remove class from all chosen elements
for (var i=0; i<elements.length; i++) {
  elements[i].className = elements[i].className.replace(reg,' ');
}

First, we create a regular expression to look for all instances of our desired class. The expression '(^| )'+myClass+'($| )' means the beginning or a space followed by myClass followed by the end or a space. The 'g' means global match, which means find all instances of the pattern.

Using our pattern, we replace the class name with a space. That way, class names in the middle of the list will remain separated, and there’s no harm done if the removed class is on the ends.

Modifying Classes the Modern Way

Browsers from IE10 and up support a property called classList, which makes an element’s classes much easier to deal with.

In a previous article, Craig Buckler provided a list of things classList can do:

document.getElementById("myelement").classList.add("myclass");

Let’s use this information to create functions that add and remove classes from all elements that match a selector.

These functions will get all desired elements, loop through them, and add or remove a class to each one.

Add Class

function addClass(selector, myClass) {

  // get all elements that match our selector
  elements = document.querySelectorAll(selector);

  // add class to all chosen elements
  for (var i=0; i<elements.length; i++) {
    elements[i].classList.add(myClass);
  }
}

// usage examples:
addClass('.class-selector', 'example-class');
addClass('#id-selector', 'example-class');

Remove Class

function removeClass(selector, myClass) {

  // get all elements that match our selector
  elements = document.querySelectorAll(selector);

  // remove class from all chosen elements
  for (var i=0; i<elements.length; i++) {
    elements[i].classList.remove(myClass);
  }
}

// usage examples:
removeClass('.class-selector', 'example-class');
removeClass('#id-selector', 'example-class');

In Summary

We’ve covered how to add and remove classes through className (the compatible way) and classList (the more modern way).

When you can control CSS classes through JavaScript, you unlock a lot of functionality including content display updates, animations, error messages, dialogs, menus, and more.

Add or Remove a CSS Class with Vanilla JavaScript

Add or Remove a CSS Class with Vanilla JavaScript Posted on 29-09-2016  Sometimes you need to add or remove a CSS class with JavaScript, and you don’t want to include an entire library like jQuery to do it 9/10 553

Comment:

To comment you must be logged in members.

Files with category

  • AngularJS and REST API

    AngularJS and REST API

    View: 84    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    This is a tutorial for those interested in a quick introduction to AngularJS and REST API. We will build the familiar Periodic Table of the Elements found in every chemistry textbook, and allow the user to select a Chemical Element by clicking on...

  • Collective Intelligence, Recommending Items Based on Similar Users' Taste

    Collective Intelligence, Recommending Items Based on Similar Users' Taste

    View: 100    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Using Collaborative Filtering to find people who share tastes, and for making automatic recommendations based on things that other people like.

  • Think Like a Bird for Better Parallel Programming

    Think Like a Bird for Better Parallel Programming

    View: 74    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Coding an application to run in parallel is hard, right? I mean, it must be hard or we’d see parallel programs everywhere. All we'd see are slick parallel apps that use every available core effortlessly. Instead multi-threaded apps are the exception...

  • Getting Started with the Bing Search APIs

    Getting Started with the Bing Search APIs

    View: 83    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Bing Search API is a set of REST interfaces that find web pages, news, images, videos, entities, related searches, spelling corrections, and more in response to queries from any programming language that can generate a web request. Applications that...

  • Brief Introduction of SocketPro High Performance and Scalable Persistent Message Queue

    Brief Introduction of SocketPro High Performance and Scalable Persistent Message Queue

    View: 279    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Continuous in-line request/result batching, real-time stream sending/processing, asynchronous data transferring and parallel computation for best performance and scalability

  • Iteration Over Java Collections with High Performance

    Iteration Over Java Collections with High Performance

    View: 73    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Java developers usually deal with Collections such as ArrayList, HashSet, Java 8 come with lambda and streaming API helps us to easily work with Collections. In most cases, we work with few thousands of items and performance isn't a concern. But in...

  • SR2JLIB - A Symbolic Regression Library for Java

    SR2JLIB - A Symbolic Regression Library for Java

    View: 73    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Grammar-Guided Genetic Programming library featuring: multi-threading, just-in-time compilation of individuals, dynamic class loading, and JNI interfacing with C/C++ code

  • Yet Another Fluent JDBC Wrapper in 200 Lines of Code

    Yet Another Fluent JDBC Wrapper in 200 Lines of Code

    View: 89    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Those who are not convinced to use Hibernate to manage persistence are forced to use plain old JDBC API. Though powerful, it requires lot of typing to get it right. For example, retrieving user data from database often requires such code snippet:

 
File suggestion for you
File top downloads
Codetitle.net - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.net Develope by Vinagon .Ltd