Can you define your own attributes for an HTML element?

I was wondering if you can define your own attributes in HTML. For example, in an HTML div there is a range of attributes such as style , title , class , etc. Can you compose and add your own while remaining syntactically correct?

For example: <div class="example" test_item="20"></div>

The need for this is related to Javascript and data.

+8
jquery syntax html attr
source share
4 answers

With one exception, no. HTML uses attributes and elements defined by the specification, and only those attributes and elements.

This exception is attributes with names starting with data- and only when you are executing an HTML 5 draft.

However, it is often advisable to encode data in the id or class attributes.

+12
source share

You can define a data attribute for any element as follows and use the jQuery data method to easily retrieve these attributes.

 <div class="example" data-mydata="mydata")></div> //In jquery to retrieve mydata you have to just say $(".example").data("mydata"); 
+3
source share

Syntactically correct - NO; however jQuery will read any attributes added to the HTML tag without any problems.

0
source share

for the record, you can add any attribute you want to add to the element with javascript using setAttribute ("name", "value")

 document.body.setAttribute("name","value"); 

and it works great. It is also basically a cross browser: quirksmode

0
source share

All Articles