3

Why is it possible to refer to an element in HTML via JS without the need to go through document? And is this recommended?

For example

index.html

<canvas id="elem" onclick="foo();">

script.js

function foo() {
    elem.width = 100;
    elem.height = 100;
}
drum
  • 5,416
  • 7
  • 57
  • 91
  • 3
    Use `onclick="foo(this)"` it will actually give you the element. Or via event properties... Try debugger to see what is hidden in the event. I think that `event.target` should give you the element too – Akxe Feb 07 '17 at 04:56
  • It's a *feature* some browser vendors implement. You should **not** rely on it as the auto-variables may be redefined by scripts – Phil Feb 07 '17 at 04:57
  • @PranavCBalan if you manage the code so that there are no global variables, then I think this is fine. Supports all modern browsers. – Mr_Green Feb 07 '17 at 04:58
  • 1
    @Akxe but even without `this` that code above will actually works – pryxen Feb 07 '17 at 04:58
  • 4
    @Mr_Green—creating global variables from element IDs has always been considered a bad feature that was introduced by ancient IE and copied by other browsers for compatibility (when IE had 95% marketshare). It should not be used. – RobG Feb 07 '17 at 05:18

0 Answers0