What is a practical maximum length for HTML id?

JavascriptHtmlCss

Javascript Problem Overview


The http://www.w3.org/TR/REC-html40/types.html#type-name">HTML spec says

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 (".").
And even though the http://www.w3.org/TR/REC-html40/sgml/sgmldecl.html#h-20.1">SGML declaration of HTML 4 uses the value 65536 for NAMELEN, it notes "Avoid fixed limits."

But surely browsers, CSS implementations, and JavaScript toolkits must have some limits on the length they support. What is the smallest such limit that is safe to use in a HTML/CSS/JS application?

Javascript Solutions


Solution 1 - Javascript

Just tested: 1M characters works on every modern browser: Chrome1, FF3, IE7, Konqueror3, Opera9, Safari3.

I suspect even longer IDs could become hard to remember.

Solution 2 - Javascript

A practical limit, for me, is however long an ID I can store in my head during the time I'm working with the HTML/CSS.

This limit is usually between 8 and 13 characters, depending on how long I've been working and if the names make sense in the context of the element.

Solution 3 - Javascript

Sometimes I will end up with very long IDs, but I name them consistently to match their exact purpose.

For example...

<div id="page">
    <div id="primary-content"></div>
    <div id="secondary-content"></div>
    <div id="search-form-and-primary-nav-wrapper">
        <form id="search-form"></form>
        <ul id="primary-nav">
            <li id="primary-nav-about-us"></li>
        </ul>
    </div>
    <a id="logo"><img /></a>
</div><!-- /#page -->

As you can see, the selectors are occasionally pretty long. But it's so much easier IMHO than working with something like the YUI grids.css where you end up with IDs like #doc, #bd, #yui-main, etc.

Solution 4 - Javascript

If this is an academic question, it's pretty interesting... but as far as best practices are concerned, you shouldn't need to -- or want to -- stretch these out. If you need to store data about an HTML element, it's better to put it into an attribute on the DOM object.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsystem PAUSEView Question on Stackoverflow
Solution 1 - JavascriptphihagView Answer on Stackoverflow
Solution 2 - JavascriptNick PrestaView Answer on Stackoverflow
Solution 3 - JavascriptMark HurdView Answer on Stackoverflow
Solution 4 - JavascriptMatt HowellView Answer on Stackoverflow