Home > Web Front-end > CSS Tutorial > Why Can't I Add Classes to SVG Elements with jQuery?

Why Can't I Add Classes to SVG Elements with jQuery?

Patricia Arquette
Release: 2024-12-27 16:06:10
Original
964 people have browsed it

Why Can't I Add Classes to SVG Elements with jQuery?

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>
Copy after login

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");
Copy after login

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");
Copy after login

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!

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