In the realm of jQuery SVG manipulation, users occasionally encounter difficulties adding or removing classes from SVG elements. A common scenario that triggers this problem is targeting SVG objects with jQuery and attempting to utilize the .addClass() method.
The code snippet provided highlights the issue:
<rect class="jimmy">
$(".jimmy").click(function() { $(this).addClass("clicked"); });
While the jQuery and SVG integration works flawlessly for event handling, class manipulation remains unsuccessful.
The root cause lies in the limited support for SVG class manipulation in jQuery versions prior to v3. This issue stems from the fact that jQuery handles SVG elements differently compared to HTML elements.
Several solutions present themselves to address this problem:
// Add class using .attr() $("#item").attr("class", "oldclass newclass"); // Remove class using .attr() $("#item").attr("class", "oldclass");
// Add class using .setAttribute() var element = document.getElementById("item"); element.setAttribute("class", "oldclass newclass"); // Remove class using .setAttribute() element.setAttribute("class", "oldclass");
The above is the detailed content of Why Doesn't jQuery AddClass() Work on SVG Elements, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!