Posts Tagged ‘removeClass’

Qlass.js – Add Or Remove Classes To Elements and NodeLists

I created the Qlass.js micro JavaScript library after having been asked during an interview with LinkedIn to write a function for adding classes to an element. After that I refined the function to work better so I could use it for something I was asked to make as part of Google’s interview process, for which I also created the hasClass() and removeClass() functions to go along with the addClass() function. Having done that, I modified the functions so they would work as a library.

To use the library, simply pass an Element or HTMLCollection to the wrapper q(), and add/remove or check if it has a class.

For example:

var div = document.getElementsByTagName('div');

q(div).addClass('my-class');
q(div).hasClass('my-class');
q(div).removeClass('my-class');

This works for getting Elements by ID as well as with querySelector() and querySelectorAll().

var elem = document.getElementById('my-element');
q(elem).addClass('new-class').hasClass('my-class');

var links = document.querySelectorAll('a');
if (q(links).hasClass('link')) {
  q(links).removeClass('link');
}

You can also just skip setting up a variable and just pass the selected item into the wrapper directly.

q(document.querySelector('element')).addClass('thisClass');

If you try to pass in something that doesn’t exist, it will just return and not do anything. So, say you select an element or NodeList of elements that aren’t in the page, nothing will be done since there is nothing that can be done.

One more thing worth mentioning is you can log to the console, whatever you try passing to the wrapper.
This will display the Element or NodeList as it is in the console of the browser.

q(div).log();

Have you ever found yourself including jQuery in a page you’re making, simply for the ease of adding a class it provides? It’s something I’ve done before, and now with this library, won’t be doing anymore.

Fork Qlass.js on Github or contribute to it if you like. Any issues or bugs you find from using it please let me know.