Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opinion: in HTML, Possible Duplicate IDs or Non-Standard Attributes?

It seems pretty common to want to let your javascript know a particular dom node corresponds to a record in the database. So, how do you do it?

One way I've seen that's pretty common is to use a class for the type and an id for the id:

<div class="thing" id="5">
<script> myThing = select(".thing#5") </script>

There's a slight html standards issue with this though -- if you have more than one type of record on the page, you may end up duplicating IDs. But that doesn't do anything bad, does it?

An alternative is to use data attributes:

<div data-thing-id="5">
<script> myThing = select("[data-thing-id=5]") </script>

This gets around the duplicate IDs problem, but it does mean you have to deal with attributes instead of IDs, which is sometimes more difficult. What do you guys think?

like image 325
Nick Retallack Avatar asked Oct 03 '08 05:10

Nick Retallack


People also ask

Can you have duplicate IDs in HTML?

Duplicate IDs are common validation errors that may break the accessibility of labels, e.g., form fields, table header cells. To fix the problem, change an ID value if it is used more than once to be sure each is unique.

What happens if two HTML elements have same ID?

As HTML and CSS are designed to be very fault tolerant, most browsers will in fact apply the specified styles to all elements given the same id. However, this is considered bad practice as it defies the W3C spec. Applying the same id to multiple elements is invalid HTML and should be avoided.

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).

What happens if ID is not unique HTML?

IDs must be unique - the same ID should not be used more than once in the same page. Otherwise, they can interfere with the user agent's (e.g. web browser, assistive technology, search engine) ability to properly parse and interpret the page.


2 Answers

Note that an ID cannot start with a digit, so:

<div class="thing" id="5">

is invalid HTML. See What are valid values for the id attribute in HTML?

In your case, I would use ID's like thing5 or thing.5.

like image 103
Peter Hilton Avatar answered Jan 01 '23 20:01

Peter Hilton


<div class="thing" id="myapp-thing-5"/>

// Get thing on the page for a particular ID
var myThing = select("#myapp-thing-5");

// Get ID for the first thing on the page
var thing_id = /myapp-thing-(\d+)/.exec ($('.thing')[0].id)[1];
like image 35
John Millikin Avatar answered Jan 01 '23 20:01

John Millikin