Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are legal characters for an HTML element id? [duplicate]

What characters can I use in an identifier for an HTML element?

For example:

<SPAN id="section[5]" ...>

(Or rather, should I stick to certain characters to make sure the id works across all major browsers/JavaScript engine).

like image 887
Tony the Pony Avatar asked Nov 22 '10 16:11

Tony the Pony


People also ask

Can I have duplicate ids in HTML?

You can't have the same id multiple times. Use class instead. Show activity on this post. COMPONENTS: if you write reusable component e.g. ) in your example then if you put two ore more components into one document then you will get INVALID html.

Do HTML ids have to be unique?

The id global attribute defines an identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).

Can HTML element have 2 ID?

An element can't have more than one ID and an ID can't be used more than once in a page.

What happens if two elements have the same ID?

If you have multiple elements with the same ID, you'll only run into problems when using JavaScript to access those elements. For example, if you were to do document. getElementById('duplicateId') , you would only get back one element instead of two. Other than that, the browser will render the page just fine.


1 Answers

In HTML5, the only restrictions are that the ID must be unique within the document, contain at least one character and contain no spaces. See http://www.w3.org/TR/2014/REC-html5-20141028/dom.html#the-id-attribute

As other answers have pointed out, HTML 4 is more restrictive and specifies that

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

like image 88
Tim Down Avatar answered Oct 03 '22 23:10

Tim Down