Is it a bad practice to add extra attributes to HTML elements?

久未见 提交于 2019-11-30 17:16:00

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; } 

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> 

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.

sfussenegger

It's invalid XHTML which is a bad thing - mainly because you can't show off with valid

;) 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 ;)

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

I don't believe it's bad practice as such, it's certainly very convenient and is exactly what you would do in an xml environment. More important is the nature of the information you hold in those custom attributes and how they are used within your code.

A nicer alternative would be to hold the data in different way for example the data() functionality of jQuery.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!