Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't HTML ids work like namespaces?

Tags:

html

It would seem natural to me that HTML would support this:

<div id="comment1">
    <div id="helpText">...</div>
</div>

<div id="comment2">
    <div id="helpText">...</div>
</div>

<div id="comment3">
    <div id="helpText">...</div>
</div>

#comment1#helpText
#comment2#helpText
#comment3#helpText

But since HTML ids must be unique, I need to do this:

<div id="comment1">
    <div id="helpText1">...</div>
</div>

<div id="comment2">
    <div id="helpText2">...</div>
</div>

<div id="comment3">
    <div id="helpText3">...</div>
</div>

#comment1#helpText1
#comment2#helpText2
#comment3#helpText3

This seems to be unnecessarily redundant, especially when I have multiple nested DIVs:

<div id="comment1">
    <div id="header1">...</div>
    <div id="introduction1">...</div>
    <div id="helpText1">...</div>
    <div id="footer1">...</div>
</div>

<div id="comment2">
    <div id="header2">...</div>
    <div id="introduction2">...</div>
    <div id="helpText2">...</div>
    <div id="footer2">...</div>
</div>

<div id="comment3">
    <div id="header3">...</div>
    <div id="introduction3">...</div>
    <div id="helpText3">...</div>
    <div id="footer3">...</div>
</div>

Can anyone give me some background as to why this is the case and perhaps some workarounds for getting HTML ids to work more along the lines of a namespace metaphor?

like image 892
Edward Tanguay Avatar asked Mar 13 '26 06:03

Edward Tanguay


1 Answers

Use class.

An id identifies that element and that element alone. It's like a pointer to an object in C++. Elements without an id are like objects without named (?) pointers to them.

Classes are like attributes. Elements may have zero or more of any combination of classes. They give you what you want.

/* CSS */
#comment1 .header
#comment3 .helpText

<!-- (X)HTML -->
<div id="comment1">
    <div class="header">...</div>
    <div class="introduction">...</div>
    <div class="helpText">...</div>
    <div class="footer">...</div>
</div>

DOM by itself does not have nice selectors for Javascript (and other scripting languages), but toolkits like JQuery allow you to select elements by class name nicely.

like image 151
strager Avatar answered Mar 17 '26 03:03

strager



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!