Sometimes I add an attribute to some of my controls. Like:
<a href id="myLlink" isClimber="True">Chris Sharma</a>
I know it is not a valid html. But it helps me in some cases.
Is this considered as a bad practice? A friend of mine says that it is ok for Intranet environment but on internet it might not be find friendly by search engines.
If it is not a good practice, what are the best practicess?
Thanks
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.
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.
来源:https://stackoverflow.com/questions/2744455/is-it-a-bad-practice-to-add-extra-attributes-to-html-elements