This is an old question, but the following may be helpful.
In principle, you can create any attributes you want, though you can’t expect the browser to know what to do with them. This is true both in HTML:
<p thing="whatever" … </p>
and in JavaScript
// p = some element
p.setAttribute('thing','whatever');
You can expect CSS to take your custom attribute seriously, as long as you use the attribute selector:
…[thing] {
…
}
Of course, if you start making up your own attributes, you run into three problems:
- An HTML validator won’t know whether your new attribute is deliberate or an error, and will assume that it’s incorrect
- You are competing with other code which is also making up its own attributes
- At some point in the future it’s possible that your made-up attribute name becomes a real-life attribute, which would cause further problems
The data-
attribute prefix has three benefits:
- HTML validators will ignore the attribute for validation purposes
- JavaScript will gather these attributes into a special
data
object for easy access
- You don’t run the risk of competing with real attribute names
Effectively the data-
prefix allows you to work with an otherwise invalid attribute by telling the validator to overlook it.
This will not solve the problem of competing attribute names, so you’re pretty much on your own. However it is common practice to at least include a prefix specific to a library.
Finally to the question of being valid.
If, by valid, you mean will it pass a standard (modern) HTML validator, the answer, is only the data-
attributes will work this way. If, on the other hand, you mean will it work, then both CSS and JavaScript will happily work with other made up attributes, as long as you don’t expect the browser to guess what you mean.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…