jQuery SVG, why can't I addClass?

前端 未结 15 1846
失恋的感觉
失恋的感觉 2020-11-22 02:25

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

The SVG:



        
15条回答
  •  长发绾君心
    2020-11-22 02:40

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

提交回复
热议问题