jQuery SVG, why can't I addClass? jQuery SVG, why can't I addClass? javascript javascript

jQuery SVG, why can't I addClass?


Edit 2016: read the next two answers.

  • JQuery 3 fixes the underlying issue
  • Vanilla JS: element.classList.add('newclass') works in modern browsers

JQuery (less than 3) can't add a class to an SVG.

.attr() works with SVG, so if you want to depend on jQuery:

// Instead of .addClass("newclass")$("#item").attr("class", "oldclass newclass");// Instead of .removeClass("newclass")$("#item").attr("class", "oldclass");

And if you don't want to depend on jQuery:

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


There is element.classList in the DOM API that works for both HTML and SVG elements. No need for jQuery SVG plugin or even jQuery.

$(".jimmy").click(function() {    this.classList.add("clicked");});


jQuery 3 does not have this problem

One of the changes listed on the jQuery 3.0 revisions is:

add SVG class manipulation (#2199, 20aaed3)

One solution for this issue would be to upgrade to jQuery 3. It works great:

var flip = true;setInterval(function() {    // Could use toggleClass, but demonstrating addClass.    if (flip) {        $('svg circle').addClass('green');    }    else {        $('svg circle').removeClass('green');    }    flip = !flip;}, 1000);
svg circle {    fill: red;    stroke: black;    stroke-width: 5;}svg circle.green {    fill: green;}
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script><svg>    <circle cx="50" cy="50" r="25" /></svg>