开发者

Can you define your own HTML element attributes?

开发者 https://www.devze.com 2023-03-25 14:39 出处:网络
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 ow开发者_如何学运维

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 ow开发者_如何学运维n, while remaining syntactically correct?

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

The need for this is with regards to Javascript and data.


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.


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");


Syntactically Correct -- NO; however, jQuery will read any attribute you add to an HTML tag without any problem.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消