0

That is to say, is it better to do this:

var firstName = document.getElementById("fname").value;

or

var firstName = document.form.fname.value;

and why?

EDIT: HTML:

input text="text" name="fname" id="fname" 
1
  • Sometimes when forms are duplicated on the page, it's easier to reference elements by "name", instead of generating unique "id"s (which are required). Commented May 5, 2013 at 1:48

3 Answers 3

4

Both work for forms, but document.getElementById also works for any other DOM element with an id, so I guess that's why it's the obvious choice today (along with newer, more flexible options such as document.querySelector).

Accessing the elements by name, however, is so ancient that it's supported even by very old browsers (such as IE4 and Netscape 2 or 3, if I recall correctly), but I doubt anyone would like/need to support those browsers nowadays.

So, there is no "better". Both work, they're just from different moments on the history of web scripting.

Sign up to request clarification or add additional context in comments.

2 Comments

Isnt using document.form.elementName faster than using DOM methods? Not that you'll actually see the difference
I don't know, maybe. Not that you'll actually see the difference :) If there were a considerable performance difference, I'm sure there would be a lot of people advocating for that, and I don't see that.
0

The first one is better because it is more readable, but in my opinion an even better way is to use jquery in which you can select using css selectors

Comments

-1

I prefer to have

<input text="text" name="fname" />

As this is less code and works, so I prefer to select by name.

But the important thing is you follow the same convention for all your project so you can navigate easily through your project.

2 Comments

I don't understand why this is getting downvotes. It's a valid opinion. Perhaps the problem is that the question is asking for opinions. Or does anybody know anything about the DOM level 0 methods being deprecated?
Note: not sure if "level 0" is the correct term for that, maybe that's only used for stuff like document.forms[] etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.