Clone
Clone

Reputation: 939

Is this a valid use of HTML IDs?

I have something like this in the html

<tr id="cart_item_1">
    <td> 
        <a href="#" id="samename" class="someclass">samename</a>
    </td>
</tr>

<tr id="cart_item_2">
    <td> 
        <a href="#" id="samename" class="someclass">samename</a>
    </td>
</tr>

Is it OK to use the samename id twice because its parent's ID is different or its completely unacceptable to use same IDS anywhere irrespective of the the hierarchy of the elements?

Upvotes: 0

Views: 54

Answers (3)

giorgio
giorgio

Reputation: 10202

No actually not. Like the name would suggest an ID or identifier needs to be unique. So you can use it to define a singular dom element. It is used for example to designate the page header, opposite some article header, which you would assign a class to. Example:

<div id="header">
    <h1>Welcome to my website!
</div>
<article class="blogpost">
    <div class="header">
        <h3>My blog post title</h3>
    </div>
    <div class="content">
        ....
    </div>
</article>
<article class="blogpost">
    <div class="header">
        <h3>My blog post title</h3>
    </div>
    <div class="content">
        ....
    </div>
</article>

Now using css you could assign styles to the page header using #header { ... } and to the post header using .header { .... }. Styles you assign to the id header won't affect a dom element with a class with the same name, and vice versa.

Basically: use an ID for elements that appear on your site only once, use classes for elements that can appear on your site multiple times.

Upvotes: 2

Quentin
Quentin

Reputation: 943163

Is it OK to use the samename id twice because its parent's ID is different

No!

or its completely unacceptable to use same IDS anywhere irrespective of the the hierarchy of the elements?

Yes.

Upvotes: 1

Brad
Brad

Reputation: 163280

IDs must be unique throughout the document, regardless of parent element.

From http://www.w3.org/TR/REC-html40/struct/global.html#h-7.5.2:

id = name [CS]

This attribute assigns a name to an element. This name must be unique in a document.

Upvotes: 4

Related Questions