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>
    <title>Title of the document</title>
    <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>
      <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">