Adding custom attributes to HTML tags

I have been using data attributes to add custom attributes in HTML. Unfortunately data is not supported in older browsers.

As an alternative, what is the disadvantage of creating custom attributes in HTML?

As an example I created carType = 'nissa' as an attribute in HTML, and I was able to parse it with javascript utilizing element.getAttribute(attributename)

It seems to work in every browser I have tested. What is the negative side to this workflow?


data- attributes are supported even in older browsers. (see the Note)

You can simply get them using the way you described:

element.getAttribute('data-xy')

The negative side of using non-standard attributes is that they make your HTML invalid. Validation is a very useful tool for finding problems in your markup. If you use the HTML5 doctype (you can safely do even in old browsers) using data- attributes will help you keep your markup valid.

More information on MDN


The issue with older browsers is the "-". Give this a try:

<div id="#selector" data-testing="my data">

var data = document.getElementById("#selector");
console.log(data.getAttribute("data-testing"));
链接地址: http://www.djcxy.com/p/88070.html

上一篇: 如何设置HTML选择的默认值?

下一篇: 将自定义属性添加到HTML标记