Can’t add/remove a class to SVG using jQuery?

I know how painful it is when you want to add/remove a class to SVG element using the normal .addClass method and see it doesn’t work!

This method is not working for SVG:

// This method is not working for SVG
$('#element').addClass("newClass");

Unfortunately, Adding, removing and toggling classes just aren’t there! But we don’t need to depends on another library! Just try one of the solutions below;

Solution using jQuery:

// Instead of .addClass("newClass")
$("#element").attr("class", "oldClass newClass");
// Instead of .removeClass("newClass")
$("#element").attr("class", "oldClass");

Another way if you don’t want to use jQuery:

var element = document.getElementById("element");
// Instead of .addClass("newclass")
element.setAttribute("class", "oldClass newClass");
// Instead of .removeClass("newClass")
element.setAttribute("class", "oldClass");