.Maui Blog

jQuery to pure Javascript examples – 2

With this post we continue the series of examples to replace jQuery with pure javascript.

Add class

// jQuery
$("#myElm").addClass("my-class");

// Pure Javascript
document.getElementById("myElm").classList.add("my-class");

Remove class from an element

// jQuery
$("#myElm").removeClass("my-class");

// Pure Javascript
document.getElementById("myElm").classList.remove("my-class");

Remove class from multiple elements

// jQuery
$(".my-elms.my-class").removeClass("my-class")

// Pure Javascript
var elems = document.querySelectorAll(".my-elms.my-class");

[].forEach.call(elems, function(el) {
    el.classList.remove("my-class");
});

// or in a line using the ES6 standard
Array.from(document.querySelectorAll('.my-elms.my-class')).forEach((el) => el.classList.remove('my-class'));

Check if an Element Contains a Class

// jQuery
$("#myElm").hasClass("my-class");

// Pure javascript
document.getElementById("myElm").classList.contains('my-class');
Exit mobile version