2

One of my colleagues doesn't like to use HTML classes and ids for javascript/jQuery purpose. Therefore I've seen that he had created custom html attribute such as

<div id="myid" class="cssClasses ..." [some-purpose-id]="mycustomId">...</div>

I asked him if it was really a good idea and he replied that he considers that classes and Ids should be reserved for styling.

Personally, I would have used classes. Some classes would have been used for styling, and some other classes would have been used for programming (jQuery selectors). The idea is to keep things appart also. And of course jQuery could set styling classes but if possible not use them for selection. Of course I also use id when appropriate but since an id is unique on a page, I like to do generic stuff using classes.

I would like to know you opinions on the better approach (if there is one). Thank you.

TTT
  • 1,848
  • 2
  • 30
  • 60
  • 2
    This is a subjective preference. There is no correct answer. – Diodeus - James MacFarlane Dec 12 '12 at 22:49
  • I would suggest you to use custom attributes. This way you will separate classes for styling only, I think separation is always better solution – karaxuna Dec 12 '12 at 22:51
  • 2
    Classes and ID's can be used for both styling and identifying the element via script. Any other script information should be stored in `data-*` attributes. It's not valid if you just *make up your own attributes* – ahren Dec 12 '12 at 22:51
  • 1
    nah, it's not subjective at all. Classes and IDs are defined in HTML, not CSS. There's no reason they should be reserved for with CSS or javascript. – marcus erronius Dec 12 '12 at 22:51
  • More variable names makes it more complicated to read. Two extra names to remember. – QuentinUK Dec 12 '12 at 22:53

6 Answers6

2

I would recommend against that, but rather use the HTML5 data attribute. Read about it here.

fuxia
  • 62,923
  • 6
  • 54
  • 62
victormejia
  • 1,174
  • 3
  • 12
  • 30
  • I still prefer to use classes, as "ahren" commented on my post "Classes and ID's can be used for both styling and identifying the element via script.". That's still my point of view. But this link about data-* was interesting. – TTT Dec 12 '12 at 23:03
1

No, for the most part, you shouldn't use made-up attributes. These are not valid HTML, and will show up as errors if you try to validate your code.

However in HTML5 you can use custom attributes that begin with data-. You can read more about them on the html5doctor website. data- attributes, however, are more often advocated for storing information, not labels. e.g. for a product you might say data-brand="gucci". Or something.

Using attributes for styling or javascript is misleading, because it's not a dichotomy. Often, you will need to add an id or class to style your markup. If possible, you can reuse these attributes to select elements in javascript without adding attributes. It keeps your code clean, but this is obviously just a preference.

If you need to select an element that doesn't already have a unique id or class that could be used for selection, you could use the data attribute. However using ids and classes is still standard practice.

Jeff
  • 12,147
  • 10
  • 51
  • 87
  • Custom attributes are only invalid against the DTD that you specify. As a matter of fact "The HTML specification states that any attribute not recognized is to be ignored by the HTML rendering engine in user agents". You can also add custom attributes to your DTD specification (if you use XHMTL DTD) – Michal Dec 12 '12 at 23:55
  • people still use xhtml? in html5 there is only one doctype and it is invalid to make up your own attributes. of course rendering engines will ignore them, but this doesn't mean it's valid html. i don't know for sure, but i would guess that all doctypes wouldn't validate with custom attributes, unless you specify them like you said. but this is no the OP's question. – Jeff Dec 13 '12 at 00:01
  • justed tested on the w3 validator for *all* versions of html and xhtml. every single one gives an error for invalid attribute name. – Jeff Dec 13 '12 at 00:10
  • http://www.w3schools.com/DTD/dtd_attributes.asp – Michal Dec 13 '12 at 01:11
  • You need to add your custom attribute for it to validate. http://www.w3schools.com/DTD/dtd_attributes.asp . And for its' many flaws XHTML still has uses such as if you need your own special mark up and it still being valid.... – Michal Dec 13 '12 at 01:27
  • i don't think OP's question is about custom doctypes, but that's useful to know, thanks – Jeff Dec 13 '12 at 02:17
1

You should use classes and IDs for both javascript and CSS. Your colleague is wrong.

It helps to remember that you want to keep separation between data (html), presentation (css styling), and behavior (javascript). Classes and IDs are there for a reason, and it's not for styling (and not for javascript, either!). They are there to allow you to semantically mark up your document.

When writing proper HTML, your classes and IDs should reflect the actual content and purpose of the data those nodes contain. Then, when you need to style them, you can specify the proper styling for, say the .zip_code class. And when you need special behavior, you can use javascript to apply the required behavior to your .deletable list items.

Of course, sometimes in the real world, there are people who feel very strongly against things, and you end up having to go along with what they want. In this case, you may have to compromise with your colleague and use HTML5's data-* attributes, as someone else suggested. However, while this is a solution that will result in valid HTML, it is not what data-* attributes were designed for, so it isn't technically the correct solution.

marcus erronius
  • 3,613
  • 1
  • 16
  • 32
  • That semantical "nature" of mark up languages is actually what I was thinking about, but with far better word. – TTT Dec 12 '12 at 23:21
  • 1
    This answer is incorrect. IDs and classes are specifically designed to uniquely identify document elements and apply styling respectively. There are plenty of examples when you deal with generated HTML where IDs and classes might have nothing to do with semantics and frankly in these situations semantics of the code add little utility. If you want to semantically mark up your CONTENT (not code) read up on http://en.wikipedia.org/wiki/Semantic_Web – Michal Dec 13 '12 at 00:01
  • No. From the HTML5 spec: "... authors are encouraged to use values that describe the nature of the content, rather than values that describe the desired presentation of the content." This is from the class attribute reference section. The id attribute section doesn't say this, but directly mentions three uses: document fragment identification, identification when scripting, and identification for styling; in that order. – marcus erronius Dec 13 '12 at 00:37
  • Of course, you will *see* code that is marked up with classes and id's from a presentational standpoint, but just because it's out there doesn't mean it's best practice :) – marcus erronius Dec 13 '12 at 00:38
  • Excellent answer. There are further uses for id attributes beyond the the three you mention in your comment. I enumerate them here: http://stackoverflow.com/questions/13001236/why-should-one-add-id-to-their-html-tags/13001519#13001519 – Alohci Dec 13 '12 at 00:56
  • 1
    @MarkHubbart Whatever the spec says you will find that in real life you will be stacking classes that reflect both the content and styling. Anyhow what I am saying is that what you are proposing creates dangerous overlaps between presentation and functionality. As these "semantic" descriptions (the semantics of which usually disappear when a dev leaves a project) in classes are incredibly easy to misinterpret (especially if a person responsible for styling has no visibility of the code) – Michal Dec 13 '12 at 01:10
0

It may be useful if you want to supply another data inside attributes for multiple purposes, look at the following example:

<script>
    function getIt(){
   ob = document.getElementById('myid') 
    alert(ob.getAttributeNode('anotherTitle').value)

    }
</script>
<div id="myid" class="cssClasses" anotherTitle="new Title">The div</div>
<a href="javascript:getIt()">Test</a>

I used the anotherTitle attribute to save or store another set of data in-which it may be used in another usage. This is a working example http://jsfiddle.net/vxknh/

The refrence: http://www.w3schools.com/jsref/prop_attr_value.asp

SaidbakR
  • 13,303
  • 20
  • 101
  • 195
  • 1
    Note that this is invalid html, since it contains an invalid attribute. This would be a good use case for HTML5's data-* attributes, i.e.: `data-anotherTitle="new Title"` – marcus erronius Dec 12 '12 at 23:14
0

Maybe your colleague was inspired by examples of the declarative style used in the dojo toolkit.

data- is a good way to "stamp" your attributes for a specific purpose (for example all dojo specific attributes are of the form data-dojo-whatever). This reduces the risk of conflict with other scripts or css.

So yes it can be a good idea, but no classes and ids are not reserved for styling.

Christophe
  • 27,383
  • 28
  • 97
  • 140
0

Classes and ID have their advantages and disadvantages (it is also very dependant on how you use them).

Classes - they were designed to convey styling info, but with advent of jQuery now they have dual purpose, sometimes signifying action (or data) and sometimes styling. This is quite confusing especially on large scale projects. Imagine a designer trying to "re-factor" the CSS and changing these class names on elements that have javascript/jQuery hooked up to it - bad things ensue. You could mitigate against that prefixing your non-styling class names with a "namespace" like ".donttouchthis-jqueryclass", which differentiates the logic from presentation is a very primitive manner. The advantage of using a class is that it can be "stacked" thus it can convey more complex "logic" than an ID for example. From a pure javascript (no jQuery) point of view reliance on classes in your code introduces some backward compatibility issues (getElementsByClassName).

IDs - as the name implies were designed to uniquely identify elements. From a programming point of view IDs offer the fastest way to access elements in the DOM (getElementById). They can also be styled, however the potential to remove an ID when re-factoring is lower (as you can always remove ID styling and give it a class). IDs are unique thus making extensive use of them to store any complex data is very, very limited. But they are great to bind click handlers or uniquely identify chunks of the DOM as long as you only need one of elements identified by them.

Both Classes and IDs have one important rule which limits their usefulness as means for conveying any business logic - they cannot start with a number (and often you just need that database id conveniently assigned to an element)

Custom attributes (not data-) - they can be anything which is kinda cool, however if you care about "validity" of your HTML you will be restricted to certain DTD types and you will need to specify them in your DTD. In reality they do not harm your HTML as browsers are specifically obliged (under the W3C convention) to ignore unknown attributes. The only problem being a clash with potential future developments. If you are using pure javascript they will also be a bit of a pain to use (but this is a subjective option - as suggested in one of the answers above this is a good supplementary option to use them as data storage). The potential for a mixup when re-factoring CSS is small.

Custom data- attributes - these are great if you are using jQuery because you can store really complex data against it (objects etc), when used correctly they really kick ass and give you a nice vocabulary to describe function of your DOM elements. "data-" namespace nicely protects it from any future conflicts with non name-spaced attributes.

Having said all that the best solution is not to overtly rely on any of these, but implement javascript patterns which allow you to pass a parent DOM element and later apply functionality to it based on markup (like a standard jQuery plugin pattern). This way you remove a lot of dependencies on specific attributes/classes/ids that are a part of static HTML source.

Michal
  • 13,439
  • 3
  • 35
  • 33