Skip to content

Instantly share code, notes, and snippets.

@EvanAgee
Created July 18, 2018 18:20
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save EvanAgee/350b5072e1ec3d82d34cc6a735914eff to your computer and use it in GitHub Desktop.
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);
}
}
};
}
});
}
@ELFrontEnd
Copy link

You can add to toggle method too.

@nuxodin
Copy link

nuxodin commented Jul 30, 2019

Or this, it fixes:

  • svgEl.classList...
  • svgEl.children
  • svgEl.contains()
  • svgEl.getElementsByClassName()
!function(){
	function copyProperty(prop, from, to){
		var desc = Object.getOwnPropertyDescriptor(from, prop);
		Object.defineProperty(to, prop, desc);
	}
	if ('classList' in HTMLElement.prototype && !('classList' in Element.prototype)) {  // ie11
		copyProperty('classList', HTMLElement.prototype, Element.prototype);
	}
	if ('children' in HTMLElement.prototype && !('children' in Element.prototype)) { // webkit, chrome, ie
		copyProperty('children', HTMLElement.prototype, Element.prototype);
	}
	if ('contains' in HTMLElement.prototype && !('contains' in Element.prototype)) { // ie11
		copyProperty('contains', HTMLElement.prototype, Element.prototype);
	}
	if ('getElementsByClassName' in HTMLElement.prototype && !('getElementsByClassName' in Element.prototype)) { // ie11
		copyProperty('getElementsByClassName', HTMLElement.prototype, Element.prototype);
	}
}();

@PavelKoroteev
Copy link

PavelKoroteev commented Aug 7, 2019

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

Does not work for me.

@gregoryedgerton
Copy link

gregoryedgerton commented Sep 28, 2020

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
Copy link

dangelion commented Nov 16, 2020

How to add toggle method too?

@PavelKoroteev
Copy link

@dangelion
Copy link

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