Search code examples
javascriptjqueryvivagraphjs

jQuery addClass not working on elements in an array


I have an array of DOM elements and I am trying to iterate through them and add a class using jQuery, but jQuery does not seem to be setting the class with the addClass method. However, the attr function still works. What am I doing wrong?

Here are my results from the console.

jQuery addclass not working

http://jsfiddle.net/kf77m/1/

line 64
$(ui).addClass("class", "js-tooltip");

Solution

  • As eithedog beat me to posting, jQuery uses element.className. The issue is that SVG elements treat the element.className value as readonly, meaning jQuery's attempt to set the class does nothing:

    if ( elem.className !== finalValue ) {
        elem.className = finalValue;
    }
    

    See https://github.com/jquery/jquery/blob/master/src/attributes/classes.js#L46

    RECT elements implement the SVGRectElement interface:

    interface SVGRectElement : SVGElement,
                               SVGTests,
                               SVGLangSpace,
                               SVGExternalResourcesRequired,
                               SVGStylable,
                               SVGTransformable {
      readonly attribute SVGAnimatedLength x;
      readonly attribute SVGAnimatedLength y;
      readonly attribute SVGAnimatedLength width;
      readonly attribute SVGAnimatedLength height;
      readonly attribute SVGAnimatedLength rx;
      readonly attribute SVGAnimatedLength ry;
    };
    

    http://www.w3.org/TR/SVG/shapes.html#InterfaceSVGRectElement

    SVGRectElement implement SVGStylable, which includes this little tidbit:

    className (readonly SVGAnimatedString)
    

    See http://www.w3.org/TR/SVG/types.html#InterfaceSVGStylable