2

I accidentally did the following and to my surprise it worked!

one.addEventListener('mouseover', myFunction);

I am assuming this is a shorthand way of doing the following:

document.getElementById('one').addEventListener('mouseover', myFunction);

I am wondering are the two equivalent and will this work in any browser?

  • 3
    Older standards say that elements having an ID become properties of the Window object with the same name. It is maintained for backwards compatibility, but you shouldn't rely on it. – Niet the Dark Absol Aug 31 '16 at 17:24
  • Are you sure that you don't have a variable "one" defined before? – mm759 Aug 31 '16 at 17:25

2 Answers2

1

Yes, both should work in any browser.

A truly short hand method of this would be to use jquery:

$("#one").on("mouseover", *yourfunctionname*);

or

$("#one").on("click", function(){
//your function code
});
john_h
  • 149
  • 1
  • 18
0

Yes this is totally possible, this is already answered in details here:

Do DOM tree elements with ids become global variables?

Community
  • 1
  • 1
Irfan Anwar
  • 1,878
  • 17
  • 30