Skip to content

Instantly share code, notes, and snippets.

@ezos86
Forked from branneman/svg-classes.js
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezos86/207d04d0fc06331771c7 to your computer and use it in GitHub Desktop.
Save ezos86/207d04d0fc06331771c7 to your computer and use it in GitHub Desktop.
//
// 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);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment