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?

Share Improve this question edited Feb 21, 2013 at 14:19 MrCode 64.5k10 gold badges92 silver badges113 bronze badges asked Feb 21, 2013 at 14:12 KroltanKroltan 5,1565 gold badges38 silver badges64 bronze badges 1
  • 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
Add a ment  | 

4 Answers 4

Reset to default 5

You 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