Can I add custom attribute to HTML tag?

2018-12-31 14:14发布

Can I add custom attribute to HTML tag like this: <tag myAttri="myVal" />

13条回答
听够珍惜
2楼-- · 2018-12-31 15:00

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.

JS Console, DevTools in Chrome

查看更多
登录 后发表回答