Can I add a custom attribute to an HTML tag like the following?
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.
No, this will break validation.
In HTML 5 you can/will be able to add custom attributes. Something like this:
<tag data-myAttri="myVal" />
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.
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>
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>
You can set properties from JavaScript.
document.getElementById("foo").myAttri = "myVal"