I still need a vanilla JavaScript solution to attach an event handler in Internet Explorer 8. When I do below code I got an error in IE8 saying:
Object doesn't support property or method 'attachEvent'
How should I fix this?
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function () {
[].forEach.call(document.querySelectorAll('input'), function (el) {
el.addEventListener('click', function (e) {
e.preventDefault();
alert('nope');
}, false);
});
})
}
else
{
var d = document.getElementsByTagName('input');
d.attachEvent('onclick', function () {
alert('no');
});
}
`, that's invalid. It must be **in** either `head` or `body`, so putting it just *before* `` makes sure it's valid, and that all of the HTML above it has been parsed into elements. (Although browsers will probably handle it if you put it in an invalid location anyway.)
– T.J. Crowder Nov 24 '15 at 12:56