Created
July 18, 2018 18:20
-
-
Save EvanAgee/350b5072e1ec3d82d34cc6a735914eff to your computer and use it in GitHub Desktop.
IE11 add/remove/contains class for SVG
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
}; | |
} | |
}); | |
} |
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);
}
}();
Toggle, if needed.
toggle: (name, flag = !this.contains(name)) {
return flag ? (this.add(name), true) : (this.remove(name), false);
}
toggle: toggle.bind(returnedObject)
Does not work for me.
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.
How to add toggle
method too?
How to add
toggle
method too?
https://gist.github.com/EvanAgee/350b5072e1ec3d82d34cc6a735914eff#gistcomment-2992240
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
You can add to toggle method too.