javascriptjquerycsssvgjquery-svg

jQuery SVG, why can't I addClass?


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.');
});

Solution

  • Edit 2016: read the next two answers.


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