Home > Web Front-end > JS Tutorial > Why Doesn\'t jQuery Add or Remove Classes from SVG Objects, and How Can I Fix It?

Why Doesn\'t jQuery Add or Remove Classes from SVG Objects, and How Can I Fix It?

Susan Sarandon
Release: 2024-11-28 06:44:13
Original
1043 people have browsed it

Why Doesn't jQuery Add or Remove Classes from SVG Objects, and How Can I Fix It?

jQuery SVG: Adding or Removing Classes to Objects

Working with jQuery SVG, you may encounter difficulties adding or removing classes from SVG objects. Here's a common mistake and its solution.

Problem:

You're trying to add a class to an SVG object, but the change doesn't appear. The SVG and jQuery functionality works as expected for other operations, such as triggering alerts upon clicks.

Code Example:

<rect>
Copy after login

Solution:

In jQuery versions earlier than 3, a known issue exists where adding or removing classes to SVG elements is not supported. To resolve this, consider using the following approaches:

  • jQuery 3: Update to jQuery version 3 or higher, which fixes this issue.
  • Vanilla JavaScript: Use the classList.add() or classList.remove() methods instead, which are supported in modern browsers:
document.getElementById("p5").classList.add("clicked");
Copy after login
  • jQuery with attr(): If you prefer to stay with jQuery, an alternative approach is to use the .attr() method:
$("#p5").attr("class", "jimmy clicked");
Copy after login

Remember that these solutions will only affect class changes specifically. Other jQuery interactions with SVG elements, such as event handling, should function as intended.

The above is the detailed content of Why Doesn\'t jQuery Add or Remove Classes from SVG Objects, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template