I have a set of SVG elements with the classes node
and link
. My program should detect whether an element has the node
class or the link
class upon hovering over any of the SVG elements. However, for some reason, the .hasClass()
doesn't seem to work:
$(".node").hover(function(evt){ console.log($(this).attr("class")); //returns "node" console.log($(this).hasClass('node')); //returns false }, function(){console.log("Done");});
So the element I hovered on has the class node
, and jQuery detects that too, as shown by console.log($(this).attr("class"));
, but for some reason the actual .hasClass()
fails. Why is this? Is it failing because of the SVG?
The reason the jQuery class manipulation functions do not work with the SVG elements is because jQuery versions prior to 3.0 use the className property for these functions. cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace ( rclass, " " ) : " " );
While jQuery is a HTML library, we agreed that class support for SVG elements could be useful. Users will now be able to call the. addClass (), . removeClass (), . toggleClass (), and. hasClass () methods on SVG. jQuery now changes the class attribute rather than the className property.
jQuery hasClass () Method Last Updated: June 4, 2021 In jQuery, if you want to find out whether some elements (or a single element) are assigned a particular CSS Class then use the.hasClass () method. It returns true when it finds the CSS class else returns false.
// Instead of .addClass ("newclass") $ ("#item").attr ("class", "oldclass newclass"); // Instead of .removeClass ("newclass") $ ("#item").attr ("class", "oldclass"); Show activity on this post. There is element.classList in the DOM API that works for both HTML and SVG elements. No need for jQuery SVG plugin or even jQuery.
The class attribute for HTML element doesn't have the same meaning in SVG.
$("<b></b>").addClass($(this).attr("class")).hasClass("node")
Or
/(^|\s)node(\s|$)/.test($(this).attr("class"))
for SVG elements.
EDIT .hasClass seems to work just fine (at least in IE9 and FF) http://jsfiddle.net/X6BPX/1/
So the problem could be any combination of the following: a syntax error, using an outdated browser, using an outdated version of jQuery.
As Bergi pointed out in comments, jQuery silently fails on SVG elements on account of className
returning an SVGAnimatedString
object instead of a normal DOMString
.
See this JSFiddle for a comparison.
I was tempted to submit a pull request on this, but did a quick project search, and apparently the jQuery project stance on SVG issues is wontfix: https://github.com/jquery/jquery/pull/1511
If you're using D3
, you could use d3.select(this).classed('node')
. Note that D3 correctly returns for both HTML elements and SVG elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With