36

Can an HTML element be assigned arbitrary attributes?

For example:

<div imMakingUpAnAttribute="whatever"></div>
1
  • Reopening, as the target dupe was asking whether custom attributes were a good idea, not whether they are possible. Commented Sep 8, 2020 at 19:51

3 Answers 3

40

Yes, you can have custom attributes:

<div imMakingUpAnAttribute="whatever"></div>

To differentiate between element and custom attributes, a good practice is to prefix it with data-.

<div data-imMakingUpAnAttribute="whatever"></div>
Sign up to request clarification or add additional context in comments.

3 Comments

the next answer has me a bit worried about this example, seeing as, according to it, the spec forbids capital letters
Arbitrary attributes are perfectly valid HTML. Do tools exist that will check your HTML for known attributes for validation? Most likely. But to say that custom attributes are themselves invalid HTML is false. Having said that, it's nevertheless preferable to use data-* attributes instead. That's what they're there for.
Makes sense. It is not ideal to say not validated just because some tools enforce it.
21

Yes, but they must be prefixed with data-.

A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen, is XML-compatible, and contains no characters in the range U+0041 to U+005A (LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z).

W3C HTML5 Spec: http://dev.w3.org/html5/spec/single-page.html?utm_source=dlvr.it&utm_medium=feed#embedding-custom-non-visible-data-with-the-data-*-attributes

Comments

2

Yes.

HTML5 custom data attributes post by John Resig http://ejohn.org/blog/html-5-data-attributes/

HTML4 attributes http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.