Reputation: 8663
I was wondering if you can define your own attributes in HTML. For example in HTML divs there's a range of attributes, such as style
, title
, class
etc. Can you make up and add your own, while remaining syntactically correct?
For example: <div class="example" test_item="20"></div>
The need for this is with regards to Javascript and data.
Upvotes: 8
Views: 6095
Reputation: 943220
With one exception — no. HTML uses the attributes and elements defined by the specification, and only those attributes and elements.
That exception is attributes with names starting data-
, and then only if you are following the HTML 5 draft.
That said, it is often appropriate to encode the data in the id
or class
attribute.
Upvotes: 12
Reputation: 69905
You can define the data attribute for any element as follows, and use jQuery data method to retrieve those attributes easily.
<div class="example" data-mydata="mydata")></div>
//In jquery to retrieve mydata you have to just say
$(".example").data("mydata");
Upvotes: 3
Reputation: 78520
for the record you can add any attribute you want to an element with javascript using setAttribute("name","value")
document.body.setAttribute("name","value");
and it works fine. This is also mostly cross browser: quirksmode
Upvotes: 0
Reputation: 5781
Syntactically Correct -- NO; however, jQuery will read any attribute you add to an HTML tag without any problem.
Upvotes: 0