Skip to content

Class related

Arthur Guiot edited this page Jul 10, 2017 · 1 revision

$.hasClass()

This function is pretty simple. You give it an element and a class name and will return you true if the element has this class name or false if the element doesn't have it.

Example

HTML:

<div class="randomClass" id="myEl"></div>

JS:

$.hasClass($.select("#myEl"), "randomClass"); // true
$.hasClass($.select("#myEl"), "anotherClass"); // false

$.addClass()

The $.addClass() function will basically add a class to an element if and only if this element doesn't have the class. It means that the $.addClass() function will call the $.hasClass() function before adding the class. But don't worry 😉, even if it calls the $.hasClass() function before adding a class, this function remains super fast 💨.

Example

HTML:

<div class="firstClass"></div>

JS:

$.addClass($.select(".firstClass"), "secondClass")
$.is($.select(".firstClass"), $.select(".secondClass")) // true

$.removeClass()

This function will verify if the element selected has the given class and if yes, will remove the class from the given element. As the 2 other functions before, this function will take 2 arguments, the first one is the element and the second one is the class name.

Example

HTML:

<div class="myClass"></div>

JS:

$.removeClass($.select(".myClass"), "myClass")

$.toggleClass()

This function is I guess the most useful function of this list because it combines all of the 3 functions we've seen before. The main goal of this function is to toggle a class, which mean that if an element doesn't have a given class, it will add this class to the element. But if the element had this class, it will remove it. This function is designed to work with events, but you can use it normally.

Example

HTML:

<div class="toToggle"></div>
<button>Toggle Class</button>

JS:

$.on($.select("button"), "click", function () {
    $.toggleClass($.select("div"), "toToggle")
})

⚠️ Questions?

Don't hesitate to ask your questions ⁉️ in the issue part 😁

Clone this wiki locally