Rob L
Rob L

Reputation: 3303

Can you use BOTH the name and id attribute in an HTML element?

Can you use both of the 'NAME' and 'ID' attributes in an HTML element?

Upvotes: 1

Views: 561

Answers (2)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201508

There is no general restriction on using both name and id attributes on an element. Unless specified otherwise, an attribute may be used independently of other attributes.

The name and id attributes have different meanings and uses. However, historically, the name attribute has been used in a role that is now better handled with the id attribute (which was introduced to HTML later on), e.g. in an img or form element, and it is declared as deprecated or obsolete in such use. The name attribute still has a completely valid and even indispensable use in controls like input and select.

There is only one case where the use of name and id on the same element has restrictions, according to HTML5 CR (clause on Obsolete but conforming features): if you use both attributes on an a element, then their values must be identical. Thus, <a name=foo id=foo> is OK (though obsolete), but <a name=foo id=bar> is not.

Upvotes: 2

Mr. B.
Mr. B.

Reputation: 8687

Yes, you can!

But notice: if you use the same name twice in a form, the first element will be overwritten.

<form method="POST">
    <input type="text" name="mytext" value="A"/>
    <input type="text" name="mytext" value="B"/>
    <input type="submit"/>
</form>

<?php
    print_r($_POST);
?>

Fiddle: http://phpfiddle.org/main/code/7ym-da9

The value of the text-input mytextwill be B.

Upvotes: -1

Related Questions