Skip to content

Instantly share code, notes, and snippets.

@branneman
Created January 15, 2014 14:12
Show Gist options
  • Save branneman/8436956 to your computer and use it in GitHub Desktop.
Save branneman/8436956 to your computer and use it in GitHub Desktop.
SVG — hasClass, addClass, removeClass, toggleClass
//
// SVG — hasClass, addClass, removeClass, toggleClass
// Source:
// https://gist.github.com/branneman/8436956
// Taken and adapted from:
// http://toddmotto.com/hacking-svg-traversing-with-ease-addclass-removeclass-toggleclass-functions/
//
if (SVGElement && SVGElement.prototype) {
SVGElement.prototype.hasClass = function (className) {
return new RegExp('(\\s|^)' + className + '(\\s|$)').test(this.getAttribute('class'));
};
SVGElement.prototype.addClass = function (className) {
if (!this.hasClass(className)) {
this.setAttribute('class', this.getAttribute('class') + ' ' + className);
}
};
SVGElement.prototype.removeClass = function (className) {
var removedClass = this.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2');
if (this.hasClass(className)) {
this.setAttribute('class', removedClass);
}
};
SVGElement.prototype.toggleClass = function (className) {
if (this.hasClass(className)) {
this.removeClass(className);
} else {
this.addClass(className);
}
};
}
@ezos86
Copy link

ezos86 commented Feb 6, 2015

Going to try this out - just what I need.. I think

@ezos86
Copy link

ezos86 commented Feb 6, 2015

didn't work :/

@sdras
Copy link

sdras commented Apr 11, 2015

I've been working with this, too. It's harder than one would think it is. Working through stuff now, I'll let you know if I find something good that works better.

@antoniobrandao
Copy link

It did work for me. Thanks

@Jakobud
Copy link

Jakobud commented Jun 25, 2015

Works great if you use vanilla JS or the array selector from jQuery:

// Works
$('#mysvg')[0].addClass('whatever');

// Doesn't work
$('#mysvg').addClass('whatever');

Look here for a jQuery shim

http://www.justinmccandless.com/blog/Patching+jQuery's+Lack+of+SVG+Support

@jbrecht
Copy link

jbrecht commented Jan 11, 2016

If you truly want to shim jquery, then toggleClass should be:

    SVGElement.prototype.toggleClass = function (className, state) {
        if (this.hasClass(className) || state===false) {
            this.removeClass(className);
        } else {
            this.addClass(className);
        }
    }; 

@mihai-craita
Copy link

You can access classList property and you can do:

SVGElement.classList.add("className");
SVGElement.classList.remove("className");
SVGElement.classList.toggle("className");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment