0

I am in the need of defining html classes from content, so pretty much every char could be used. According to html reference I may use cdata, so I should not run into problems. I figure though, that css and/or javascript/jquery won't play nicely with that.

Anyone has experience with what chars can be used without problems or if there is a function/plugin/.. that tidies the class names, so that they are usable?

harpax
  • 5,986
  • 5
  • 35
  • 49
  • It seems HTML has a much broader definition of a valid class than CSS does. According to the [W3C Validator](http://validator.w3.org/), `:foo`, `-foo`, `!foo`, `.foo`, `$foo`, and `@foo` are all valid classes. That could potentially be quite useful for [DOM-based templating engines](http://stackoverflow.com/q/9282315/116639)! – Tom Anderson Aug 16 '12 at 17:53

2 Answers2

5

css classnames must be the usual identifiers (http://www.w3.org/TR/CSS21/syndata.html#characters)

In CSS 2.1, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [A-Za-z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit.

Javascript doesn't mind, since you will use classnames as Strings. So you can use any character as far as javascript is concerned.

If you want to strip your classnames down to the usable css subset, a simple regexp should be enough. If you want to encode your classnames into the same subset, it will be a little tougher, but I suppose you can try to Base64-encode them. Here are some jQuery plugins for base64 encoding/decoding.

Alsciende
  • 26,583
  • 9
  • 51
  • 67
  • Since he didn't ask for a specific version, it's interesting to know that classes used to be separated by periods in [HTML 3](http://www.w3.org/MarkUp/html3/html3.txt). – Knu May 27 '15 at 23:07
1

As far as the class attribute is concerned you will run into problems using chars other than [a-z], [A-Z] and [_-].

For arbitrary data I would recommend the (upcoming with HTML5) data-x attribute.
See http://ejohn.org/blog/html-5-data-attributes/ for an example.

Cheers

aefxx
  • 24,835
  • 6
  • 45
  • 55