Skip to content Skip to sidebar Skip to footer

Is It A Bad Practice To Add Extra Attributes To HTML Elements?

Sometimes I add an attribute to some of my controls. Like: Chris Sharma I know it is not a valid html. But it helps me in som

Solution 1:

If you are using HTML5 doctype then you can add data attrbutes which are valid.

So something like the following will be valid

<a href id="myLlink" data-isClimber="True">Chris Sharma</a>

Solution 2:

Yes. It is considered a bad practice. Your HTML (if it's 4.0) won't validate successfully. Instead, add a class like so:

<a href id="myLlink" class="climber" >...</a>

Remember that you can have multiple classes:

<a href id="myLlink" class="climber girl pretty" >...</a>

And you can use CSS or JQuery to select out stuff based on these classes, and selectively override style based on the combinations:

a.climber             { color: brown; }
a.climber.girl        { color: red; }
a.climber.girl.pretty { color: pink; }

Solution 3:

It is not a best nor a good practice.

I guess you need it for some javascript treatment. I usually solve the problem by adding custom "class" attribute, prefixed with 'js'.

Another solution is to use the store data/retrieve data functionnality of JQuery, or the equivalent of any other framework, which imply echoing all over your generated HTML.


Solution 4:

It's invalid XHTML which is a bad thing - mainly because you can't show off with valid XHTML ;) Every mainstream browser and search engine will ignore extra attributes happily though. You could add an extra namespace though to make your XHTML valid again.

<html xmlns:my="http://example.com">
  <!-- SNIP -->
  <a href id="myLlink" my:isClimber="True">Chris Sharma</a>
  <!-- SNIP -->
</html>

That's perfectly valid XHTML. However, W3C Validator will still refuse to validate it (I think). It's a shortcoming of their XML parser. For such non namespace aware parsers, my:isClimber will still be treated as would be isClimber. But you can now rest easy as you know that it is valid XML and finally that's what counts, isn't it ;)


Solution 5:

Using jquery,

to store: $('#element_id').data('extra_tag', 'extra_info');

to retrieve: $('#element_id').data('extra_tag');

This was also posted @ [http://stackoverflow.com/a/16985773/2458978][1]

[1]: How to store arbitrary data for some HTML tags


Post a Comment for "Is It A Bad Practice To Add Extra Attributes To HTML Elements?"