jQuery SVG: Troubleshooting the Inability to addClass
When working with jQuery SVG, you may encounter issues adding or removing classes from SVG objects. In this article, we will investigate the causes and provide solutions.
The Problem:
Consider the following code:
<rect>
Despite being able to trigger an alert when clicking the object, adding the "clicked" class fails.
The Solution:
Prior to jQuery 3, adding classes to SVG elements was problematic. However, this issue has been resolved in jQuery 3. Additionally, modern browsers support the vanilla JavaScript classList.add('newclass') method for SVG elements.
Alternative jQuery Approach:
If you prefer to stick with jQuery, you can manipulate the class attribute directly using attr():
// Add "newclass" $("#item").attr("class", "oldclass newclass"); // Remove "newclass" $("#item").attr("class", "oldclass");
Vanilla JavaScript Approach:
To avoid jQuery dependency, use the following vanilla JavaScript code:
var element = document.getElementById("item"); // Add "newclass" element.setAttribute("class", "oldclass newclass"); // Remove "newclass" element.setAttribute("class", "oldclass");
The above is the detailed content of Why Can't I Add Classes to SVG Elements with jQuery?. For more information, please follow other related articles on the PHP Chinese website!