'HTMLElement' is undefined in IE8, an alternative?

别说谁变了你拦得住时间么 提交于 2020-01-06 02:18:27

问题


Hey all I have methods like this:

// Has Class
HTMLElement.prototype.hasClass = function (searchClass) {
    return this.className.match(new RegExp('(\\s|^)' + searchClass + '(\\s|$)'));
}

In IE9 it works fine. In IE8 it gives me undefined... is there a simple work around?


回答1:


You can't add methods to HTMLElement.prototype in older versions of IE if I remember correctly. A simple workaround would be:

var hasClass = function (el, searchClass) {
    return el.className.test(new RegExp('(\\s|^)' + searchClass + '(\\s|$)'));
};

And used like:

alert(    hasClass(   document.getElementById('div1'), 'classToCheck'   )    )

DEMO

You can always add this to the Object.prototype object but it's frowned on



来源:https://stackoverflow.com/questions/8868004/htmlelement-is-undefined-in-ie8-an-alternative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!