Skip to content

Instantly share code, notes, and snippets.

@EvanAgee
Created July 18, 2018 18:20
Show Gist options
  • Select an option

  • Save EvanAgee/350b5072e1ec3d82d34cc6a735914eff to your computer and use it in GitHub Desktop.

Select an option

Save EvanAgee/350b5072e1ec3d82d34cc6a735914eff to your computer and use it in GitHub Desktop.
IE11 add/remove/contains class for SVG
if (!("classList" in SVGElement.prototype)) {
Object.defineProperty(SVGElement.prototype, "classList", {
get() {
return {
contains: className => {
return this.className.baseVal.split(" ").indexOf(className) !== -1;
},
add: className => {
return this.setAttribute('class', this.getAttribute('class') + ' ' + className);
},
remove: className => {
var removedClass = this.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2');
if (this.classList.contains(className)) {
this.setAttribute('class', removedClass);
}
}
};
}
});
}
@PavelKoroteev

PavelKoroteev commented Aug 7, 2019

Copy link
Copy Markdown

Toggle, if needed.

toggle: (name, flag = !this.contains(name)) {
    return flag ? (this.add(name), true) : (this.remove(name), false);
}

toggle: toggle.bind(returnedObject)

@MisterMarlu

Copy link
Copy Markdown

Does not work for me.

@gregoryedgerton

gregoryedgerton commented Sep 28, 2020

Copy link
Copy Markdown

Has anyone thought about how to incorporate Replace? Looking to avoid refactoring but potentially could make existing codebase work with Add or Remove so this is very much appreciated.

@dangelion

dangelion commented Nov 16, 2020

Copy link
Copy Markdown

How to add toggle method too?

@PavelKoroteev

Copy link
Copy Markdown

@dangelion

Copy link
Copy Markdown

I saw that but don't get how to implement in the original gist

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