HTML5 specification allows almost any id attribute value - use wisely

Original author: Roger Johansson
  • Transfer
As I mentioned some time ago in the article “ Creating the correct id ”, HTML 4.01 is quite limited in terms of valid id attribute values:
The ID and NAME attributes must begin with a letter ([A-Za-z]), followed by any number of letters, numbers ([0-9]), hyphens ("-"), underscores ("_"), colons (":") and periods (".").

HTML5 allows the use of almost any id attribute value: HTML5
specification 3.2.3.1 about id attribute :
The value must be unique with respect to all other ID values ​​within the element tree containing this and must contain at least one character. The value must not contain spaces.
At least one character, no spaces.

This allows you to use special characters as values ​​of the id attribute. And it gives us a lot of opportunities to put ourselves in an idiotic position, since we can use values ​​that will cause problems with both CSS and JavaScript, if you are not careful.

Consider the following HTML code:


CSS selector conflicts


To access the above elements using CSS, using the normal syntax will fail:
##id {}
#div>p+p:first-child {}


Since id contains a character for which there is a predefined value in CSS, you will need to conjure CSS selectors a bit to make them work as they should. One way is to use a selector by attribute value, instead of #:
[id="#id"] {}
[id="div>p+p:first-child"] {}


Another way is to escape conflict-causing characters:
#\#id {}
#div\>p\+p\:first-child {}


JavaScript issues


If you use a JavaScript library, like jQuery, to work on our elements, this will cause difficulties:
$("#div>p+p:first-child").css("fontSize", "2em");


As with CSS, you have to escape special characters:
$("#div\\>p\\+p\\:first-child").css("fontSize", "2em");


Meaningful naming of elements


HTML5 gives us great freedom in choosing the id attribute values ​​of elements. It can be sometimes useful. But, in my opinion, using characters that conflict with CSS and JavaScript means simply asking for trouble. The same thing with the use of cool characters, instead of normal readable text. Use if advantages will prevail over risks. But you should not use the new naming capabilities just because you can.

Also popular now: