jQuery SVG, why can't I addClass?

Don P picture Don P · Dec 26, 2011 · Viewed 121.2k times · Source

I am using jQuery SVG. I can't add or remove a class to an object. Anyone know my mistake?

The SVG:

<rect class="jimmy" id="p5" x="200" y="200" width="100" height="100" />

The jQuery that won't add the class:

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

I know the SVG and jQuery are working together fine because I can target the object and fire an alert when it's clicked:

$(".jimmy").click(function() {
    alert('Handler for .click() called.');
});

Answer

forresto picture forresto · Apr 21, 2012

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");