Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add a custom attribute to an HTML tag?

Can I add a custom attribute to an HTML tag like the following?

<tag myAttri="myVal" /> 
like image 849
lovespring Avatar asked Nov 14 '09 19:11

lovespring


People also ask

Can HTML elements have custom attributes?

Every HTML element may have any number of custom data attributes specified, with any value.

Are custom tags allowed in HTML?

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.

How the attributes are added to the HTML tag?

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.

What is the recommended way to add custom HTML5 attributes?

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.


2 Answers

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-.

like image 164
Gumbo Avatar answered Oct 13 '22 05:10

Gumbo


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.

like image 34
carillonator Avatar answered Oct 13 '22 06:10

carillonator