Can I add a custom attribute to an HTML tag?
Can I add a custom attribute to an HTML tag?
Question
Can I add a custom attribute to an HTML tag like the following?
<tag myAttri="myVal" />
Accepted Answer
You can amend your !DOCTYPE declaration (i.e. DTD) to allow it, so that the [XML] document will still be valid:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
[
<!ATTLIST tag myAttri CDATA #IMPLIED>
]>
#IMPLIED
means it is an optional attribute, or you could use #REQUIRED
, etc.
More information is in DTD - Attributes.
Popular Answer
You can add custom attributes to your elements at will. But that will make your document invalid.
In HTML 5 you will have the opportunity to use custom data attributes prefixed with data-
.
Read more... Read less...
The jQuery data()
function allows you to associate arbitrary data with DOM elements. Here's an example.
In HTML5: yes: use the data- attribute.
<ul>
<li data-animal-type="bird">Owl</li>
<li data-animal-type="fish">Salmon</li>
<li data-animal-type="spider">Tarantula</li>
</ul>
Yes, you can do it!
Having the next HTML
tag:
<tag key="value"/>
We can access their attributes with JavaScript
:
element.getAttribute('key'); // Getter
element.setAttribute('key', 'value'); // Setter
Element.setAttribute()
put the attribute in the HTML
tag if not exist. So, you dont need to declare it in the HTML
code if you are going to set it with JavaScript
.
key
: could be any name you desire for the attribute, while is not already used for the current tag.
value
: it's always a string containing what you need.