Can I add a custom attribute to an HTML tag?
Asked Answered
C

18

419

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

<tag myAttri="myVal" />
Consciousness answered 14/11, 2009 at 19:6 Comment(5)
#432674Berneicebernelle
and also #209928Berneicebernelle
possible duplicate of Custom attributes - Yea or nay?Ronel
Though the answers say "yes," make sure you have a themed set of attributes that arent likely to be used with plug-ins. eg: "data-myuniqueattribute." I usually just prefix anything after "data-" with some type of two letter abbreviation. eg: "data-yscolumntype." Keep it unique.Kafka
MDN has a good resources for data-attributes, can refer for more info: developer.mozilla.org/en-US/docs/Learn/HTML/Howto/…Micron
F
199

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.

Flock answered 14/11, 2009 at 22:15 Comment(12)
Need I create a DTD file or just add ATTLIST inline in html file?Consciousness
just put all that at the top of your html file (assuming xhtml 1.0 transitional is ok)Flock
Maybe I am missing something, but if you follow this approach, the ]> shows up in the rendered web page. Happening to me on Firefox 3.6. This snippet from alistapart.com/articles/customdtd seems to verify this behavior: "If you download the sample files for this article and validate file internal.html, you can see this for yourself. Unfortunately, when you display the file in a browser, the ]> shows up on the screen. There’s no way around this bug, so this approach is right out."Folly
A couple of things that could help with the "]>" appearances: Save the file with a .xhtml filename extension. Include the MIME type in the file with <meta http-equiv="content-type" content="application/xhtml+xml" />.Welch
@LS I have same problem but after adding MIME type still getting "]>" character in body.Flyman
Declaring the attribute is pointless as far as browser behavior is considered. They do not read the DTD. Moreover, they cannot even properly skip the internal subset (which is used here), which explains the “]>” meass. The declaration would be relevant to formal validation only, and should not be used on production pages.Inland
Yes got the same problem - ]>. So is there any way to make it valid without DTD or with default DTD (whatever it is in Chrome)Puduns
This answer only applies to XHTML and HTML 4.01 and older. It completely misses that you can now create your own attributes if you prefix them with data-.Sybil
Remember that you're not serving XHTML unless your webserver is sending the document as XHTML (application/xhtml+xml) in the header. Most people that use the XHTML doctype only do so to put the browser into standards mode and aren't really serving XHTML to the browser, but HTML instead.Ambary
i added this already. but my problem is my custom attribute has a capital letter in it and when i create the element with the custom attribute it is all lower case. how come?Disentitle
@NoahPassalacqua that is expected behavior see w3c.github.io/html/…Hypochondriasis
Does this allow accessing via JavaScript?Congeries
B
363

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

Bullion answered 14/11, 2009 at 19:14 Comment(11)
Remember "invalid" means nothing. The page will render fine 100% of the time.Shoup
Actually "invalid" has very real-world implications. E.g. it can put your document into quirksmode rendering. At any rate, use the HTML5 doctype and you'll be valid.Sybil
There is a good table of different doctypes and corresponding browser modes here: hsivonen.fi/doctype/#handling. HTML5 doctype switches all post-2001 browsers into (Full) Standards mode. XHTML Transitional and HTML 4 Transitional (especially without DTD) doctypes do not:)Combine
holy sweet christ, thank you. @jfar right but it decreases readability.Brianbriana
My document is invalid anyways, because it tells me | is not allowed in a css href, but that's what's necessary for Google FontsClustered
@kim366 I suggest \escaping the | like so: \|Estremadura
@Noface interesting solution, I was thinking about urlencoding it to %7CClustered
@Noface Ah, nice. I'm actually using pug, not HTML, and the backslash seems to have zero effect on the resulting HTML codeClustered
@Noface There we go: href='https://fonts.googleapis.com/css?family=Some+Font|Another+Font|Third+Font'.replace(/\|/g, '%7C')Clustered
great. i recommend precompiling your template to html wherever possible as it will load faster and hit your server less.Estremadura
The link has been changed. It is now : html.spec.whatwg.org/…*-attributesAvogadro
F
199

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.

Flock answered 14/11, 2009 at 22:15 Comment(12)
Need I create a DTD file or just add ATTLIST inline in html file?Consciousness
just put all that at the top of your html file (assuming xhtml 1.0 transitional is ok)Flock
Maybe I am missing something, but if you follow this approach, the ]> shows up in the rendered web page. Happening to me on Firefox 3.6. This snippet from alistapart.com/articles/customdtd seems to verify this behavior: "If you download the sample files for this article and validate file internal.html, you can see this for yourself. Unfortunately, when you display the file in a browser, the ]> shows up on the screen. There’s no way around this bug, so this approach is right out."Folly
A couple of things that could help with the "]>" appearances: Save the file with a .xhtml filename extension. Include the MIME type in the file with <meta http-equiv="content-type" content="application/xhtml+xml" />.Welch
@LS I have same problem but after adding MIME type still getting "]>" character in body.Flyman
Declaring the attribute is pointless as far as browser behavior is considered. They do not read the DTD. Moreover, they cannot even properly skip the internal subset (which is used here), which explains the “]>” meass. The declaration would be relevant to formal validation only, and should not be used on production pages.Inland
Yes got the same problem - ]>. So is there any way to make it valid without DTD or with default DTD (whatever it is in Chrome)Puduns
This answer only applies to XHTML and HTML 4.01 and older. It completely misses that you can now create your own attributes if you prefix them with data-.Sybil
Remember that you're not serving XHTML unless your webserver is sending the document as XHTML (application/xhtml+xml) in the header. Most people that use the XHTML doctype only do so to put the browser into standards mode and aren't really serving XHTML to the browser, but HTML instead.Ambary
i added this already. but my problem is my custom attribute has a capital letter in it and when i create the element with the custom attribute it is all lower case. how come?Disentitle
@NoahPassalacqua that is expected behavior see w3c.github.io/html/…Hypochondriasis
Does this allow accessing via JavaScript?Congeries
U
93

No, this will break validation.

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

<tag data-myAttri="myVal" />
Uncanonical answered 14/11, 2009 at 19:8 Comment(8)
but, I don't care validation, I just wanna it could be accessed by javascript.Consciousness
It will work of course. But deliberately creating invalid documents is not such a good idea.Uncanonical
Well technically it's not html any more. Equally you could add a load of binary in the middle of a tag - but it won't be html.Tui
While you can, you have to ask yourself if there is a better way to accomplish what you need. Why do you need to set custom attributes to access it in Javascript?Graig
Creating invalid documents is a great idea. Google creates them to reduce load times, every site using canvas uses them to create a better user experience, and using javascript frameworks to pull meaningful data off of html elements is much easier using the custom attribute technique.Shoup
@jfar: Canvas is not invalid. It's not in HTML 4.01; however, it is a perfectly legal part of the upcoming HTML5 specification.Woodpecker
What do you mean "not invalid"? Its not part of any accepted specification. How can something be valid against a specification that does not exist?Shoup
The spec mentions not to use upper case letters, so it'd be <tag data-myattri="myVal" />Dusk
T
34

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

Tui answered 14/11, 2009 at 19:23 Comment(2)
This is golden.Halfcock
in case no jQuery library is loaded, it's easy in pure/vanilla javascript to use Element.getAttribute(), Element.setAttribute(), or Element.dataset developer.mozilla.org/en-US/docs/Web/API/HTMLElement/datasetBetaine
A
28

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> 
Ataghan answered 1/4, 2017 at 20:11 Comment(1)
Better authority:developer.mozilla.org/en-US/docs/Learn/HTML/Howto/…Cronk
U
22

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 don't 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.

Unclassified answered 25/8, 2014 at 12:55 Comment(1)
For the HTML to be valid, it's better to prefix key with data-.Waylen
P
13

var demo = document.getElementById("demo")
console.log(demo.dataset.myvar)
// or
alert(demo.dataset.myvar)
//this will show in console the value of myvar
<div id="demo" data-myvar="foo">anything</div>
Pick answered 18/10, 2017 at 22:39 Comment(1)
Please add short explanation to your answer.Shirberg
R
11

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

Rani answered 14/11, 2009 at 19:11 Comment(4)
Depends on what you define HTML as. I think of HTML as a language based on SGML, with a specific set of elements and attributes. XHTML is a variant on XML, with a specific set of elements and attributes that's a lot like HTML's. When you use your own attributes, it is still SGML of XML, but no longer HTML of XHTML in my opinion.Wakeup
Take it as an adhoc extension, not a standard in a strict sense, but a sort of an implementation of the requirement that it shouldn't fail parsing if it contains custom attributes.Rani
DouweM: Of course, there's always the HTML serialization of HTML5, which is neither SGML nor XML.Woodpecker
And you broke (invalidated) the document in the process. Not good practice.Flock
M
6

You can set properties from JavaScript.

document.getElementById("foo").myAttri = "myVal"
Monsignor answered 14/11, 2009 at 22:46 Comment(1)
That's just adding a variable attached to an element. That is not a custom attribute in the HTML.Laud
J
5

use data-any , I use them a lot

<aside data-area="asidetop" data-type="responsive" class="top">
Joaquinajoash answered 30/8, 2019 at 6:12 Comment(2)
How do you get data-* values from JavaScript?Congeries
elem.dataset.area in the case of the above example. For attributes with additional dashes, make the key camelCase. eg. data-box-area="30px" becomes elem.dataset.boxArea.Felsite
G
4

Here is the example:

document.getElementsByTagName("html").foo="bar"

Here is another example how to set custom attributes into body tag element:

document.getElementsByTagName('body')[0].dataset.attr1 = "foo";
document.getElementsByTagName('body')[0].dataset.attr2 = "bar";

Then read the attribute by:

attr1 = document.getElementsByTagName('body')[0].dataset.attr1
attr2 = document.getElementsByTagName('body')[0].dataset.attr2

You can test above code in Console in DevTools, e.g.

JS Console, DevTools in Chrome

Guillerminaguillermo answered 3/8, 2017 at 12:13 Comment(0)
L
4

Yes, you can use data-* attribute. The data-* attribute is used to store custom data private to the page or application.

<ul>
    <li data-pageNumber="1"> 1 </li>
    <li data-pageNumber="2"> 2 </li>  
    <li data-pageNumber="3"> 3 </li>  
</ul
Lassa answered 20/8, 2020 at 9:36 Comment(1)
And then you can access these idiomatically in JSClancy
R
4

With custom elements, it is common to add custom attributes without data- prefix.

Here is an example from HTML standard: Custom elements (note the country attribute):

<flag-icon country="nl"></flag-icon>

Another example from MDN Web Docs: Using custom elements (note the l and c attributes):

<custom-square l="100" c="red"></custom-square>
Retrench answered 28/2, 2022 at 19:9 Comment(0)
C
2

well! you can actually create a bunch of custom HTML attributes by disguising the data attributes in what you actually want.

eg.

[attribute='value']{
   color:red;
}
<span attribute="value" >hello world</span>

It apparently works but that would invalidate your document, there is no need of using JScript for you to have custom attributes or even elements unless you have to, you just need to treat your new formulated(custom) attributes just the same way you treat your "data" attribute

Remember "invalid" does not mean anything. The document will load fine at all the time. and some browsers would actually validate your document only by the presence of DOCTYPE....., you actually know what I mean.

Cadell answered 20/5, 2020 at 9:43 Comment(0)
C
1

Another approach, which is clean and will keep the document valid, is to concatenate the data you want into another tag e.g. id, then use split to take what you want when you want it.

<html>
<script>
  function demonstrate(){
    var x = document.getElementById("example data").querySelectorAll("input");
    console.log(x);
    for(i=0;i<x.length;i++){
      var line_to_illustrate = x[i].id  + ":" + document.getElementById ( x[i].id ).value;
      //concatenated values
      console.log("this is all together: " + line_to_illustrate); 
      //split values
      var split_line_to_illustrate = line_to_illustrate.split(":");
      for(j=0;j<split_line_to_illustrate.length;j++){
        console.log("item " + j+ " is: " + split_line_to_illustrate[j]);
      }      
    }
  }
</script> 

<body>

<div id="example data">
  <!-- consider the id values representing a 'from-to' relationship -->
  <input id="1:2" type="number" name="quantity" min="0" max="9" value="2">
  <input id="1:4" type="number" name="quantity" min="0" max="9" value="1">
  <input id="3:6" type="number" name="quantity" min="0" max="9" value="5">  
</div>

<input type="button" name="" id="?" value="show me" onclick="demonstrate()"/>

</body>
</html>
Clayson answered 13/12, 2016 at 16:36 Comment(0)
A
0

I can think of a handy use for the custom tag "init". Include a JavaScript expression that gets evaluated at document.onLoad() time and provides a value for the tag, e.g.

<p>&lt;p&gt;The UTC date is &lt;span init="new Date().toUTCString()"&gt;?&lt;/span&gt;.&lt;p&gt;</p>

Some boilerplate JavaScript code would scan all the tags in the DOM at document.onload() time looking for the init attributes, evaluating the expressions that they contain, and assigning them to the containing tag's innerHTML. This would give HTML some of the power of JSP, PHP etc. Currently we have to split the HTML markup and the JavaScript code that illuminates it. Bugs love split code.

Almemar answered 27/10, 2020 at 8:1 Comment(0)
F
-1

You can add, but then you have to write a line of JavaScript code too,

document.createElement('tag');

to make sure everything fall in place. I mean Internet Explorer :)

Freemanfreemartin answered 19/11, 2012 at 9:27 Comment(3)
This would be relevant if the tag name is not known to IE. Here the issue is a custom attribute, not a custom tag; the word “tag” in <tag ...> here apparently means just any HTML tag.Inland
Doesn't this also invalidate XHTML (unless it's a recognised tag)?Liana
The question asks about custom attributes, not custom elements.Whiteman
B
-9

You can do something like this to extract the value you want from JavaScript instead of an attribute:

<a href='#' class='click'>
    <span style='display:none;'>value for JavaScript</span>some text
</a>
Bacillus answered 1/6, 2015 at 6:5 Comment(1)
Attributes exist for a reason; as do things like <input type="hidden" value="...">. Consider, though, the difference between the type of data you put in various attributes by contrast to the data you might put in a hidden field. Hiding a <span> (of all things) in an <a> for the sake of maintaining a piece of metadata is not a good move. It would be peculiar to your site and very much dependent on JS (graceful degradation, people).Filum

© 2022 - 2024 — McMap. All rights reserved.