I am looking for a way to do node.classList.contains("foo")
in Internet Exploder 7-9 without needing to refactor major portions of my code. This method is present in all other browsers (even IE10).
I have found Code with classList does not work in IE? but I dont understand how I would use this for replacing the .contains()
method.
I already do have code that let's me run isolated code for certain browsers only, so giving IE some extra or different code isn't a problem.
Is there a way to add said method via classList
's prototype or some other handy way to work with className
?
This just isn't possible.
At first glance, you'd have thought you'd have been able to patch your own classList
implementation into HTMLElement
if it didn't exist already;
if (!("classList" in document.createElement("div"))) {
HTMLElement.prototype.classList = {
contains: function () {
}
};
}
However:
contains
implementation has no way to access the DOMElement (this
is the classList
object, not the elementYour only option is to replace all your usage of classList
with your own wrapper function, which uses the classList
functionality if available, and falls back to your own implementation if it doesn't.
var classListWrapper = (function () {
if ("classList" in document.createElement("div")) {
return {
add: function (el, class) {
el.className.add(class);
},
remove: function (el, class) {
el.className.remove(class);
},
// etc.
}
} else {
return {
add: function (el, class) {
el.className += ' ' + class;
},
remove: function (el, class) {
el.className = (' ' + el.className + ' ').replace(' ' + class + ' ', ' ');
},
// etc.
};
}
}());
... and then in your code use classListWrapper.add(element, class)
instead.