Explain Codes LogoExplain Codes Logo

Html: Valid id attribute values?

html
id-attributes
best-practices
css-integration
Anton ShumikhinbyAnton Shumikhin·Aug 3, 2024
TLDR

In HTML, an id attribute should begin with a letter (A-Z/a-z) or an underscore (_). It can include letters, numbers, hyphens, underscores, colons, and periods. You must ensure that there is no whitespace present. Here's a correct example:

<!-- this id is like a secret agent - it has a user code and a mission profile --> <div id="user-123_profile"></div>

Avoid "bad practices" like this:

<!-- this id is like a covert agent who forgot his training - don't let him loose! --> <div id="123user"></div>

The value of unique IDs

Always remember: id values should be unique within a single HTML document. It's like people: everyone needs to have their own unique name to distinguish themselves. No duplicate names allowed - even twins need different names!

Dealing with special characters

Brace yourselves when using special characters like periods or colons in your id values. They might be perceived differently in CSS or JavaScript. It's akin to a spy using codenames - you need to escape them properly with a backslash in CSS (\#my.id for my.id) and a double backslash in jQuery ($("#my\\.id")).

The sensitive case of XHTML

Keep in mind that in XHTML, unlike HTML5, id values are case-sensitive. Just as we consider 'John' different from 'john', XHTML does the same with id values. Be cautious with these case surprises!

Compatibility matters: No leading digits

Are we still following HTML4 compatibility? Then let's not have our id start with a number. Preserving these good old standards is like respecting your elders - it ensures broad family (read: browser) support!

Making the right choice with ID Naming

Coding is all about clean practices. Follow a consistent id naming strategy to maintain sanity in large projects and aid communication with fellow devs. Remember: An organised desk is a happy desk!

Best practices for JS/CSS integration

When interacting with JS and CSS systems, specific id formatting is key. It's like courting: you need to give them the right signals (formatting). Avoid characters that carry specific semantics in these languages, like the hash symbol (#).

Organising your ID armory

An organised system smoothes out development and future refactoring for id attributes. It's like having a well-organized toolshed: you can find whatever you need instantly. Consider using methodologies like BEM (Block Element Modifier) for this purposе.

Case sensitivity in different landscapes

Though in HTML5, cases in id values are irrelevant, do be cautious with certain doctypes or XML applications that are case-sensitive. Cases really do matter here: #myId, #MYID, and #MyID would be seen as three different entities.