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