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.