admin管理员组文章数量:1332361
For examlpe, if I have this:
<div id="blah" myattribute="something">whatever</div>
Can I be safe that no browsers will ignore (and thus render inaccessible from legacy JavaScript) the myattribute
? I am aware that this is ugly and not standard, but is quite useful. Or if they do, would jQuery still be able to get them?
For examlpe, if I have this:
<div id="blah" myattribute="something">whatever</div>
Can I be safe that no browsers will ignore (and thus render inaccessible from legacy JavaScript) the myattribute
? I am aware that this is ugly and not standard, but is quite useful. Or if they do, would jQuery still be able to get them?
-
You'll most likely be able to use
node.getAttribute('my attribute')
to retrieve the value,node.setAttribute('my attribute')
to set the value. – David Thomas Commented Feb 21, 2013 at 14:16
4 Answers
Reset to default 5You should use data
attributes, they're web standard.
Like this:
<div id="blah" data-myattribute="something">whatever</div>
Then in jQuery you can do:
var value = $("#blah").data("myattribute");
Browsers won't plain about unrecognized attributes, and Javascript and jQuery will still be able to access them:
console.log( $('#blah').attr('myattribute') ); // something
console.log( document.getElementById('blah').getAttribute('myattribute') ); // something
However you should use the HTML5 data-*
attribute which is specifically for the purpose of custom attributes. jQuery has the data()
method for accessing/setting them:
<div id="blah" data-myattribute="something">whatever</div>
<script>
console.log( $('#blah').data('myattribute') ); // something
</script>
Why don't use the data-attributes Data-attributes, HTML5?
The browser will ignore invalid attributes. If you want to specify your own attributes use the data- attribute as this is recognized as valid.
w3 docs on data attribute
http://www.w3/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes
本文标签: javascriptHow browsers handle invalidunspecified attributes on HTML elementsStack Overflow
版权声明:本文标题:javascript - How browsers handle invalidunspecified attributes on HTML elements? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742318789a2452358.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论