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
Patricia ArquetteOriginal
2024-12-27 16:06:10972browse

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>

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!

Statement:
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