Advertisement
Advertisement


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" />
2019/07/07
1
352
7/7/2019 2:15:01 PM

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.

2019/07/07
189
7/7/2019 2:11:15 PM


No, this will break validation.

In HTML 5 you can/will be able to add custom attributes. Something like this:

<tag data-myAttri="myVal" />
2009/11/14

The jQuery data() function allows you to associate arbitrary data with DOM elements. Here's an example.

2019/07/07

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> 
2017/04/01

Yes, you can, you did it in the question itself: <html myAttri="myVal"/>.

2009/11/14

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.

2019/07/30

Source: https://stackoverflow.com/questions/1735230
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]