Can I add a custom attribute to an HTML tag like the following?
<tag myAttri="myVal" />
Every HTML element may have any number of custom data attributes specified, with any value.
All standard rules of HTML elements apply to custom elements. Just like standard elements, you can create a custom element in the DOM using JavaScript, or declare it in HTML.
Attributes define additional characteristics or properties of the element such as width and height of an image. Attributes are always specified in the start tag (or opening tag) and usually consists of name/value pairs like name="value" . Attribute values should always be enclosed in quotation marks.
You can use getAttribute() and setAttribute() in JavaScript to get and set the value of different data attributes. The getAttribute method will either return null or an empty string if the given attribute does not exist. Here is an example of using these methods: var restaurant = document.
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-
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With