Name vs Id attribute in HTML

Here are some differences between both:

  1. name has never been a div element attribute.

  2. name as used on the form controls (input, textarea, select, and button elements) is radically different from the id attribute on named elements. In this case, the name attribute relates to how data is labeled when sent to server, and multiple elements may share the same name.

    The id attribute on the other hand is for identifying one unique element for the purposes of scripting, styling, or addressing.

  3. The use of the name attribute on other elements than form controls was in HTML 4.01 the same as that of id, but it allowed for a wider set of characters than the id attribute and wasn't controlled in quite the same way. Because of this ambiguity the W3C decided to deprecate/remove the name attribute on those elements in favor for the unambigous id attribute in XHTML.

    This is also connected to another detail of XML however - only one attribute of any element may be of the type ID, which would not be the case if they let name stay on the element, but corrected the ambiguity problems.

  4. As the name attribute didn't work the same on those two sets of elements, it was best to remove one of them.

In short, for backwards compatibility, you should use the name and id attribute both, both set to the same value, for all elements except form controls if you use HTML 4.01 or XHTML 1.0 Transitional. If you use XHTML 1.0 Strict or later you should use only id. For form controls, you should use name for what you want the form to send to the server and for DOM 0 access, and only use id for styling, DOM1-3 access or addressing reasons


They are not interchangeable, even if they sometimes appear to be.

Name should only exist on form input fields. It is what that tag will cause the browser to pass in the submission as the name of the field. As Tomalak noted in a comment, DIV actually does not have a Name attribute.

ID is the unique identifier for the DOM, to manipulate or refer to the tag; for example, in JavaScript.


It depends on where you are going to use them.

Usually, id of an element is unique while multiple elements can share the same name.

Id is referenced as #here, and name is referenced as [name=here].

Tags:

Html