w3docs logo
  1. Snippets
  2. HTML
  3. What is the Difference Between the "id" and "name" Attributes

What is the Difference Between the "id" and "name" Attributes

If you have a situation when you must decide whether to use the HTML id or name attribute, then you are in the right place.

In this snippet, we’re going to discuss the differences between the id and name attributes, after which you’ll make a better decision of their usage.

Let’s discuss them separately and then you can see an example.

The id Attribute

The id attribute is a unique identifier of the HTML element. Each id attribute must be unique. Also, this attribute must begin with a letter and is case sensitive. It can be used as an anchor reference in URL. It isn’t associated with the data within the element.

In CSS, the id attribute is referenced with the # character. In Javascript, it is referenced with getElementById().

The name Attribute

The name attribute defines a name of the element. It is used in the HTTP request that is sent to the server as a variable name by the browser. This attribute is associated with the data within the element.

Like the id attribute, the name attribute must begin with a letter and is case sensitive, but unlike the id attribute, it can be not unique.

The name attribute cannot be referenced in CSS. In Javascript, it is referenced with getElementsByName().

This attribute is valid only on the following elements: <button>, <fieldset>, <form>, <iframe>, <input>, <map>, <meta>, <object>, <output>, <param>, <select>, and <textarea>.

Example of the id and name attributes:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h1>Radio Buttons</h1>
    <form action="/form/submit" method="post">
      <p>Select your gender:</p>
      <input type="radio" id="male" name="gender" value="male">
      <label for="male">Male</label><br>
      <input type="radio" id="female" name="gender" value="female">
      <label for="female">Female</label><br>
      <input type="radio" id="other" name="gender" value="other">
      <label for="other">Other</label>
      <br>
      <p>Select your age:</p>
      <input type="radio" id="age1" name="age" value="30">
      <label for="age1">0 - 25</label><br>
      <input type="radio" id="age2" name="age" value="60">
      <label for="age2">25 - 50</label><br>
      <input type="radio" id="age3" name="age" value="100">
      <label for="age3">50 - 80</label><br><br>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>
Do you find this helpful?