Is it OK to add your own attributes to HTML elements? [duplicate] - javascript

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Custom attributes - Yay or nay?
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?
In current learning project I am working on, I need to add an attribute whose value will be a number. At first I thought of using "id" for this purpose but an answer revealed that it is not good to do that.
Is it OK if I create my own attribute, say "messid" and assign a numeric value such as "12", "6" etc to it?
Here is why I want to do this so that you can correct me if I am doing it totally wrong:
I need to access this number in my JavaScript (using jQuery). Just taking the value of attribute is easy but extracting the numeric value from a string like "m12" or "m6" is a pain. (I am a beginner in JavaScript world.)

There has been much discussion about this:
Custom attributes - Yay or nay?
How to store arbitrary data for some HTML tags
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?
At the end of the day, I am on the camp that believes data attributes are the best way to go. They are being introducted in HTML5 to avoid name conflicts. Essentially, if you want to store anything data related you just prepend "data-" on the attribute name:
<div class="user" data-userid="5"></div>
The only con to the whole thing is then that your XHTML won't validate, but I honestly don't care about that stuff. (That's right, I said it)

In HTML 5 you're allowed to add any attribute starting with data-, so e.g. <div data-messid="12"> is OK.
HTML 4 and XHTML 1 won't validate if you add your own attribute, but besides that nothing bad will happen if you choose attribute name unique enough (so it won't conflict with any current or future HTML attribute).

Just so you know, you can easily extract an ID from a string like m12 or m6, I would do it like this:
//name the IDs m_12, m_3 etc
var number = $('#someElement').attr('id').split('_')[1];
Or if say, you have a bunch of links with numbers in the ID as above, and all the links have the clickMe class:
$('a.clickMe').click(function() {
alert($(this).attr('id').split('_')[1]);
});

I use custom attributes, and since they are supported by all browsers I checked I think it is not bad to use them. You can also use custom HTML tags to simulate HTML5, with some IE hack, so why not use attributes, if they don't need any hacks?
Anyway, you can read similar discussion here:
Custom attributes - Yea or nay?

This isn't a definitive answer, but having had to do this in the past I can say this not only works well, it is cross-browser friendly.

If using jQuery you can use .data to store custom information against an element.
The downside of custom attributes are:
IE6 creates extra objects to store custom 'expando' attributes these have a tendency to leak especially if they are created via script.
validation issues

No - it's not.

Related

Properly hardcode Javascript variables into HTML

I realize my title isn't perfectly clear, but I couldn't come up with a better one. So here goes:
I work on an e-commerce website where different products should have different maximum order ammounts. Since writing plugins for the CMS is not really an option, I want to solve this with javascript.
What I want to do:
Check wether a div with the class "order-limit" exists
Read that divs data-limit-attribute, which contains a number
Add a sentence including the number
Now today I read http://danwebb.net/2010/1/27/put-that-data-attribute-away-son-you-might-hurt-someone which basically said:
Don't use data-* attributes for javascript.
So now I wonder: What's the best practice to do what I did, given that products have different upper limits?
I think this quote from the article you've linked is self-explanatory enough:
By all means, use data-* attributes to add semantically valuable data
to your HTML but if you are just using it to prop up a script you are
writing think again.
By the way, I don't believe there's a BEST way, only the best way for your specific situation and needs.

Using the # inside a CSS id declaration

Normally i would only use alphanumeric with - and _ in any html class or id attribute, but i wondered whether it was possible it include a # in the middle of an attribute, e.g:
<div id = "my_css_id_#f4ed11">
I wont't be a targeting this through CSS, this is purely for javasrcipt.
NOTE The reason I am asking it not because I want to do this, but because of some related PHP code done by someone it would make this part of the project easier.
Thanks
Sure you can. It’s valid as per HTML5.
You’ll simply need to escape the character in a selector (for use in CSS or JavaScript). For the # character, it’s quite simple; you can just use \#.
Here’s a tool that will tell you how to escape any character in a CSS/JS selector: http://mothereff.in/css-escapes#0foo%23bar From that page:
<script>
// document.getElementById or similar
document.getElementById('foo#bar');
// document.querySelector or similar
$('#foo\\#bar');
</script>
P.S. On the subject of weird characters in ID or class values: http://mathiasbynens.be/notes/html5-id-class
I wouldn't recommend doing that. It would be difficult to access an element with ID #...#... via CSS or even Javascript as you noted since # is so overloaded in programming/coding.
It sounds like you want to store some piece of data. You are aware that W3C standards allow attributes that begin with data- right?
For instance, you could keep a piece of data associated with an element as such:
<p data-name="John Jones">I like alliteration.</p>
This article details data attributes effectively.
http://ejohn.org/blog/html-5-data-attributes/
It would be best to do trial and error and see if it works. But, in terms of pseudo-selectors, there should be no problem with have the # symbol. To select you would use:
$("#my_css_id_#f4ed11")

What are some good reasons for not using custom tag attributes such <a my_att='...'>

I'm doing this mainly to store data inside tags as I echo it out of php, and then using jQuery to $(..).attr('my_att') to retrieve it.
It hasn't caused any problems so far, but are there good reasons (other than it's not valid) why we shouldn't do this?
Because you can use valid custom attributes instead:
<div data-customer-id="3" class="customer"> [...] </div>
If you prefix your attributes with data- they are valid HTML. The reason for not just writing your own attributes is that they can wind up inheriting meaning in the future. Obviously this is unlikely for some cases (like "customer-name"), but using the prefix is safter.
Another added benefit is that you are very clear about your intentions; another developer isn't going to come by and think you meant to write kind="text" rather than type="text" when you were trying to mark the model associated with a particular input field.
I prefer to do that sort of thing as HTML5 data attributes.
Then you can use jQuery.data() to get at the attributes if you're in a browser that doesn't support data attributes natively.
For example:
<a href="#" id="MyLink" data-address="1600 Pennsylvania Ave, Washington, DC">
My Address
</a>
Then I can do $('#MyLink').data('address') to get the value back.
I see mainly two reasons to avoid using custom attributes :
1° If the browser is really strict about the HTML standard, he can simply refuse to show a page which don't comply to the DTD or worse, crash trying to display your page.
2° The browser can choose to strip unknown attribute from the element.
Sure, actually, no browser do either of these things, but who can say what new implementations will do in the future ?
Standards are developed for a reason, and it's always a good idea to follow them. Especially when HTML5 let you create custom attributes so easily.

<img> Attributes

I've got some java script code that implements a kind of slide show. It uses a series of img tags as a table to control its actions. I probably used some code I found some where as a basis. Anyway, the img tags contain a data-img attribute which I can't find in any definition of the img tag. Now I find I need to add more data to the img tags. So my questions are:
1) Is the data-img actually a real attribute or something adhoc?
2) Can I invent yet more attributes?
3) What is the danger of using such attributes?
1) It's valid in HTML 5; it is an invalid attribute (that will, as far as I know, still work in all browsers, it but will break validation) in HTML 4
2) As far as I am aware, you can add arbitrary attributes and query them in Javascript, but chances are those attributes will not survive certain DOM manipulation and other operations where the browser creates markup - it's possible the invalid attributes will simply be dropped
3) Your pages will no longer validate.
Background: Custom attributes - Yay or nay?
Depends on implementation.
YES, its often quite useful to do so.
If created in #2, not really, no, they are part of the DOM at that point, i know of no browser that removes attributes.
They are a valid HTML5 attributes.
If you need to add and get that data only with javascript for client side without communicating with the server side you can implement a store and retrieve mechanism similar to the one used by Mootools.
It doesn't pollute the DOM and store also javascript objects.

Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?

HTML (or maybe just XHTML?) is relatively strict when it comes to non-standard attributes on tags. If they aren't part of the spec, then your code is considered non-compliant.
Non-standard attributes can be fairly useful for passing along meta-data to Javascript however. For instance, if a link is suppose to show a popup, you can set the name of the popup in an attribute:
<a href="#null" class="popup" title="See the Popup!"
popup_title="Title for My Popup">click me</a>
Alternatively, you can store the title for the popup in a hidden element, like a span:
<style>
.popup .title { display: none; }
</style>
<a href="#null" title="See the Popup!" class="popup">
click me
<span class="title">Title for My Popup</span>
</a>
I am torn however as to which should be a preferred method. The first method is more concise and, I'm guessing, doesn't screw with search engines and screen readers as much. Conversely, the second option makes storing large amounts of data easier and is thus, more versatile. It is also standards compliant.
I am curious what this communities thoughts are. How do you handle a situation like this? Does the simplicity of the first method outweigh the potential downsides (if there are any)?
I am a big fan of the proposed HTML 5 solution (data- prefixed attributes). Edit: I'd add that there are probably better examples for the use of custom attributes. For instance, data that a custom application will use that have no analogue in standard attributes (eg. customization for event handlers based on something that can't necessarily be expressed in a className or id).
Custom attributes provide a convenient way to carry extra data to the client side. Dojo Toolkit is doing this regularly and it has been pointed (Debunking Dojo Toolkit Myths) out that:
Custom attributes have always been
valid HTML, they just don’t validate
when tested against a DTD. [...] The
HTML specification states that any
attribute not recognized is to be
ignored by the HTML rendering engine
in user agents, and Dojo optionally
takes advantage of this to improve
ease of development.
Another option would be to define something like this in Javascript:
<script type="text/javascript">
var link_titles = {link1: "Title 1", link2: "Title 2"};
</script>
Then you can use this later in your Javascript code, assuming your link has an ID that corresponds to the ID in this hashtable.
It doesn't have the disadvantages of the other two methods: no non-standard attributes nor the ugly hidden span.
The disadvantage is that it might a bit of an overkill for things as simple as your example. But for more complex scenarios, where you have more data to pass, it's a good choice. Especially considering that the data is being passed as JSON, so you can pass complex objects with ease.
Also, you keep data separate from the formatting, which is a good thing for maintainability.
You can even have something like this (which you can't really do with the other methods):
var poi_types = {1: "City", 2: "Restaurant"};
var poi = {1: {lat: X, lng: Y, name: "Beijing", type: 1}, 2: {lat: A, lng: B, name: "Hatsune", type: 2}};
...
<a id="poi-2" href="/poi/2/">Hatsune</a>
And since you most probably use some server-side programming language, this hash table should be trivial to generate dynamically (just serialize it to JSON and spit it in the header section of the page).
Well in this case, the optimal solution is
click
and using title attribute.
Sometimes I break the spec if I really need it. But rarely, and only for good reason.
EDIT: Not sure why the -1, but I was pointing out that sometimes you think you need to break spec, when you don't.
Why not declaring the popup_title attribute in a custom DTD ? This solves the problem with validation. I do this with every non-standard elements, attributes and values and thank this validation shows me only real problems with my code. This makes also any browser errors less possible with such HTML.
You could nest hidden input elements INSIDE the anchor element
<a id="anchor_id">
<input type="hidden" class="articleid" value="5">
Link text here
</a>
Then you can easily pull the data out by
$('#anchor_id .articleid').val()
My solution in the end was to hide additional data in the id tag separated by some sort of delimiter (one underscore is a space, two is the end of that arg), the second arg there is an id:
click
Ugly, and it assumes you're not already using the id tag for something else, but it is compliant across every browser.
My personal feeling in your example is that the span route is more appropriate, as it meets the standards of the XHTML specification. However, i can see an argment for custom attributes, but I think they add a level of confusion that isn't needed.
I've been racking my brain over this as well. I like the readability of non-standard attributes, but I don't like that it will break standard. The hidden span example is compliant, but it is not very readable. What about this:
click
Here the code is very readable, because of JSON's key/value pair notation. You can tell that this is meta data that belongs link just by looking at it. The only flaw I can see beside hijacking the "rel" attribute is that this would get messy for complex objects. I really like that idea of "data-" prefixed attributes mentioned above. Do any current browsers support this?
Here is something else to think about. How much impact does not compliant code have on SEO?

Categories