html: name vs. id

2019-09-20

 | 

~2 min read

 | 

235 words

In looking into labels for web forms recently, I stumbled on a question I really didn’t know the answer to: What’s the difference between a name and an id attribute in HTML?1

After some research, the way I’m thinking about it is: Names are used for naming a thing (duh). But like a name for a person, it doesn’t have to be unique. IDs, on the other hand, should be unique.

This was greatly informed by the discussion on StackOverflow.2

There’s no relationship implied between a name and an id. The fact that many examples across the web have the same name and id is an artifact of the example. It’s not required.

Consider a form to determine a user’s favorite color via radio buttons. Only one radio can be selected at a time, but each element would refer to the favorite color on submission. So the name = "favorite" while the id is unique.

In that way, names can be used to group like things.

<form>
  <label> Name <input name="name" id="name" type="text" /></label><br />
  <label>
    Favorite Color <br />
    <input name="favorite" id="favorite-red" type="radio" label="red" />red
    <br />
    <input name="favorite" id="favorite-blue" type="radio" label="blue" />blue
    <br />
  </label>
  <input type="submit" value="submit" />
</form>

Here’s a sample codepen3

Footnotes



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!