wha...">

How do browsers handle invalid / unspecified attributes on HTML elements?

For example, if I have this:

<div id="blah" myattribute="something">whatever</div> 

Can I be safe that no browser will ignore (and thus make inaccessible from the old JavaScript) myattribute ? I know this is ugly and not standard, but quite useful. Or, if they do, can jQuery get them?

+4
source share
4 answers

Browsers will not complain 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 must use the HTML5 data-* attribute, which is specifically designed for custom attributes. jQuery has a data() method to access / set:

 <div id="blah" data-myattribute="something">whatever</div> <script> console.log( $('#blah').data('myattribute') ); // something </script> 
+3
source

You should use data attributes, this is the web standard.

Like this:

 <div id="blah" data-myattribute="something">whatever</div> 

Then in jQuery you can do:

 var value = $("#blah").data("myattribute"); 
+5
source
+2
source

Invalid attributes will be ignored in the browser. If you want to specify your own attributes, use the data attribute, as it is recognized as valid.

w3 docs by data attribute

http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes

+1
source

All Articles