0

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');
    });
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rahul Chakrabarty
  • 2,149
  • 7
  • 39
  • 70

1 Answers1

2

getElementsByTagName returns a collection of elements, not a single element. The collection doesn't have attachEvent. The individual elements do (on older IE).


Note also that:

  • Your IE-specific branch doesn't wait for the full DOM to be parsed as your standards branch does. Either both should, or both should not, but not a mix. Best practice is not to use DOMContentLoaded and just put the script at the end of the HTML, immediately prior to the closing </body> tag.

  • Your IE event handler isn't preventing the default action, whereas your standards one is.

If you want a cross-browser event attaching function, here's one in another answer on SO.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • even though I do `` and `var d = document.getElementById('bu');` I'm getting the same error. I tried with putting script after – Rahul Chakrabarty Nov 24 '15 at 12:53
  • 2
    @Riki—as TJ said, your *attachEvent* branch is called immediately, it doesn't wait for the DOM to be ready like the *addEventListener* branch does. – RobG Nov 24 '15 at 12:55
  • 1
    @Riki: And don't put the script *after* `

    `, 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
  • @Riki: Finally, I wouldn't absolutely guarantee that IE wouldn't have some incredibly stupid (in)compatibility mode where `document` didn't have `addEventListener` but elements did. I'd check on an element, not `document`. (`document.body` is probably a good choice.) – T.J. Crowder Nov 24 '15 at 12:58