0

So I am new to javascript, and I know how to access DOM elements using getElementByXxx() methods. But in one example I saw that it's possible to access elements directly using their name or like:

<!DOCTYPE html>
<html>
<body>
    <form name="myForm"><input type="button" id="btn"></form>
    <script>
    console.log(document.myForm);
    console.log(document.myForm.btn);
    </script>
</body>
</html>

Console:

<form name="myForm">
    <input type="button" id="btn">
</form>
<input type="button" id="btn">

Which is very confusing to me. Google and online courses only say about getElementById(), querySelector(), and objects (and object collections). I really don't understand how this works. When I change to id for form it doesn't work

<!DOCTYPE html>
<html>
<body>
    <form id="myForm"><input type="button" id="btn"></form>
    <script>
    console.log(document.myForm);
    console.log(document.myForm.btn);
    </script>
</body>
</html>

Console:

undefined
Uncaught TypeError: Cannot read property 'btn' of undefined

Also it seems like it only work with form and input, and not for paragraph or div. Am I missing some obvious things here? I'm sorry if my question is too basic.

LeafLover
  • 33
  • 3
  • Don't rely on automatic references to DOM elements, they can easily be overridden with global variables. Always use a proper query method to fetch a reference. – Teemu Apr 05 '21 at 15:48
  • I definitely prefer `getElementById()` and `querySelector()`, but you said one example shows "that it's possible to access elements directly using their **name** like...". However, you have only given the elements an **id**, not a name. – mykaf Apr 05 '21 at 15:48
  • More info https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables – James Apr 05 '21 at 16:07
  • @user1599011 Sorry I should be clear that both name and id are in the example. Edited. – LeafLover Apr 06 '21 at 14:10
  • @James Thank you so much. It makes so much sense for me now. – LeafLover Apr 06 '21 at 14:11

0 Answers0