Javascript - Shorthand method of getting element by ID

时间:2016-08-31 17:22:27

标签: javascript html getelementbyid addeventlistener

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?

2 个答案:

答案 0 :(得分:0)

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

Do DOM tree elements with ids become global variables?

答案 1 :(得分:0)

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
});