While jQuery SVG provides a convenient way to interact with SVG elements, users may encounter difficulties adding or removing classes to SVG objects. This issue stem from jQuery's inability to handle class attributes on SVG elements prior to version 3.
The provided SVG code:
<rect>
And the jQuery code:
$(".jimmy").click(function() { $(this).addClass("clicked"); });
demonstrates the inability of jQuery to add the "clicked" class to the SVG rect. Despite being able to trigger an alert when the object is clicked, adding or removing classes fails.
Option 1: Upgrade to jQuery 3 or Higher
jQuery 3 introduced significant improvements in its SVG handling capabilities, including the ability to manipulate class attributes. Upgrading to jQuery 3 or later should resolve this issue.
Option 2: Use .attr() or setAttribute() for jQuery or Vanilla JS, Respectively
Without upgrading to jQuery 3, you can use the .attr() method in jQuery or the setAttribute() method in vanilla JavaScript to modify SVG class attributes.
jQuery
$("#item").attr("class", "oldclass newclass"); // Add a class $("#item").attr("class", "oldclass"); // Remove a class
Vanilla JavaScript
var element = document.getElementById("item"); element.setAttribute("class", "oldclass newclass"); // Add a class element.setAttribute("class", "oldclass"); // Remove a class
By using these alternative approaches, you can successfully add or remove classes from SVG elements in jQuery or vanilla JavaScript, even without upgrading to jQuery 3.
The above is the detailed content of Why Doesn\'t jQuery addClass() Work with SVG Elements, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!