Given HTML like this:
<body>
<form name="myForm" action="savedata.php" method="post">
<input type="text" name="myName" />
</form>
</body>
Using document.getElementById, I would acces the input calledmyName` like this:
var getName = document.getElementById('myName').value;
But, instead, I know I can do this, and I like it better:
var getName = document.myForm.myName.value;
Does this second method have a way? And, is it ok to use myForm.myName or should I use getElementById?
First off, your first bit of “DOM” code is wrong.
getElementById('myName');isn’t going to get the element you want, since it has noid– just anameattribute. Similarly, I don’t believe your tree-navigating second bit of code will work since elements are stored byid, not byname.Now, dismissing that, both examples you posted are “DOM”. You have a document which is structured as a tree of node objects. You’re navigating it as such. The former snippet (were it to be written correctly) is just a more standard means of access.
As for what you should do (I’m assuming from the tags you’re asking about JavaScript code in particular): either way works. The first idea (insofar as it uses
getElementById) is better because a change in your document structure won’t break it, but if it’s you who’ll be mopping up the broken glass, it’s all your show.To illustrate my point, let’s say you put the
inputelement in adiv. Code usinggetElementByIdwould still work. Code navigating the tree downward would not, since it doesn’t have a property-get to go through the new intervening element. Thus, you’ve coupled your logic to your display – and that’s a code smell.Take a look at jQuery if you don’t already know about it; it, and similar libraries, make JavaScript a much more pleasant language in which to develop.