-5

I have just started learning to code.

Code A and B

Code B does not use Document.selectSomething per say and yet works, it seems to me the id of an element can be used directly to add event listeners without having to document select the element then adding event listeners

JJJ
  • 32,902
  • 20
  • 89
  • 102

1 Answers1

0

Because if you try to access a DOM element directly will give you an error if the element doesn't exist. But accessing it through getElementById selector will return null. And because elements with an id which contains dashes like 'my-id' can't be accessed directly.

Kronen
  • 369
  • 9
  • 23
  • thanks for answering, but actually both code B and Code A work with no errors generated anywhere in the console – Mohamed Jadib Feb 03 '18 at 15:12
  • you can with bracket notation off window.... https://jsfiddle.net/pn10gx4f/ – epascarello Feb 03 '18 at 15:14
  • @epascarello Yep, I know, but I thought by directly he was refering to exactly the way he shows in his examples – Kronen Feb 03 '18 at 18:15
  • 1
    @Mohamed Jadib I was answering your question 'Why use code A when code B works perfectly it seems?'. In your example it works because the id exists in your DOM, this is not about it working or not, (although I told you the difference of giving an error vs returning null) it's about using best practices. – Kronen Feb 03 '18 at 18:19
  • @Kronen I read more about it and I get it now, it is about best practices – Mohamed Jadib Feb 08 '18 at 22:33