Should HTML element classes have prefixes depending on their use? - javascript

I've been told that it's standard practice to prefix class names on HTML elements with "jq" or "js" so that the designer doesn't conflict with the developer.
I've been around a little and I've never seen this done and personally feel this creates an artificial and unhelpful divide between design and code.
The question is whether this is indeed standard practice, and moreover, I would like references to articles explaining why this is done (what problem does it solve).

I'm the front-end developer at my organisation and as such am responsible for the CSS. I create all the required classes for layout and UI, as well as periodically tidying up unused styles and mark-up.
Our developers never need to add classes for presentation, but they do occasionally add classes for Javascript. In these instances I have asked them to prepend their classes with js-.
This simply helps me identify classes that are not used for presentation, but are still required for functionality. My other class names are all descriptive of the content.
Before we introduced this it was much harder to keep the mark-up tidy (by removing unused classes) as classes could seem redundant (with no references in the stylesheets), but were still used.
I've not come across any documentation saying this is a bad idea. It works for us, so is simply a matter of personal preference.

This sounds like an old fashioned convention for me especially in context with html/javscript/css.
Classes should only be used for layout reasons. If there are classes anyway, defined by a designer, then they can and should be used by developers. Values for pure programm controls should be defined using custom attributes (http://www.javascriptkit.com/dhtmltutors/customattributes.shtml). This practice together with detailed and well-thought-out naming conventions mostly avoid problems.
It also sounds like classes would have to be assigned to elements twice often with this prefix pratice. One more reason to ask how a practice like that can be a good or even standard one.
Edit:
Prefixes can be useful inside plugins for e.g. javascript libraries of course to avoid class conflicts!

It's not a general standard practice, but it may be a standard practive within a specific organisation.
Using prefixes to specify usage of an identifier is called hungarian notation. It's mostly used to specify data types in script languages without strict typing, but the original intention was just to specify any aspect that was crucial to the use of the identifier.
Using prefixes like that can be useful to make sure that classes intended for design doesn't conflict with classes intended for program control. It's however not dependant on who is creating the class, but how the class is used. If a developer creates a script that adds a class to elements to change their appearence, the class is used for design so it should not be prefixed as a program control class name. A class name used for program control would only be used for that, and have no visual style applied to it.
As with most programming practices, it's more important that you pick a standard and stick to it, than picking the standard that is absolutely best.

Not only is it not standard practice (except, presumably, in your organisation), but the W3C advises against it. Class names should be used to further describe the contents of semantic HTML tags, rather than as reference points for design or development.
I would expect well-structure HTML pages to have consistent classes for similar content types which would be perfectly suitable for JavaScript usage.
A designer who cannot write HTML correctly, remembering that the HTML markup is supposed to describe the content not style it, should not be writing HTML IMO.

I've certainly not heard of this as a 'standard' practice. Reading guidelines and articles, I have never seen a prefix infront of a class.
However, it might be handy prefixing a class name if you were going to use that class with jQuery. It will be easier to identify and also it would let others know that it used by a function.

Related

Any standard function to code complex identifier for using it the html element id/class/name?

Do we have any preferred/standard way to "encode" complex identifiers e.g {Source:"ARCH.1", Code: "456-789.456 A+", SubNumber:##2} for using in HTML elements id, class, name attributes?
I can invent something, but may be there is universal well know solution that is:
stable
is ease to decode
generates tokens that are still readable and is easy to use in css
selectors
Based on what I think your question is...you may be mixing concerns and creating extra dependencies. With your approach, if the data changes form, you may need to change your JS and CSS too or you will face a broken design. I don't think you want that.
If you need an identifier in the HTML for a data hook (for AJAX calls), there are data- attributes that may be used, but I would not recommend using a combination of these as a hook to styling. Instead, I would stick to classes.

Should I select DOM elements via id/class names or data attributes?

A co-worker suggested to change our full JavaScript code to select DOM elements only via data attribute instead of id/class names.
He says, this is bad:
$('#foo')
$('.bar')
And this is good:
$('[data-foo]')
I didn't know that there is a benefit to this so I googled up a bit and found these two blog posts:
Contra data attributes: http://intuio.at/en/blog/dont-use-data-attributes-to-find-html-elements-with-js/
Pro: http://roytomeij.com/blog/2012/dont-use-class-names-to-find-HTML-elements-with-JS.html
Since these blog articles are just opinions of two developers I'd like to know what's the actual practical experience with this? Is there a real benefit to using data-attributes for DOM selection or is it a stupid idea?
$('#foo') is fastest, but with an id only ONE element can have the Id
$('.bar') is faster than data-attributes, but are messy because class usually is associated with css styling
$('[data-foo]') is the slowest (marginally) but is the least likely to interfere with other actions
speed test - http://jsperf.com/data-selector-performance
Why You Should Use Data Attributes
If you use jQuery only, your whole logic will be bound to the DOM really closely. In big projects problems will occur. Your designer does probably think about a new naming convention and this will result in borken jQuery code. Lower performance is only a problem for a huge DOM or large amounts of selectors. Using data-attributes gives you a better seperation of styling and logic/controllers.
Why You Should NOT Use Data Attributes
jQuery itself was built for DOM manipulation mainly and therefore the tight bonding was somehow intended. Meaning the site was probably already built or designed and you want to manipulate it afterwards. If your focus is on architecture, test-driven development, maintenance and you want to achieve a better seperation of design and logic there are frameworks such as angularjs, which have indeed their own kind of data attributes (ng-directives). So there is probably a better choice if you want to think in terms of architecture.

What is encapsulation in context of JavaScript?

What is encapsulation in context of JavaScript? I'm confused after reading this statement in mozilla web-site(link):
Encapsulation
In the previous example, Student does not need to know how the Person
class's walk() method is implemented, but still can use that method;
the Student class doesn't need to explicitly define that method unless
we want to change it. This is called encapsulation, by which every
class inherits the methods of its parent and only needs to define
things it wishes to change.
I've understood encapsulation as hiding class members, but in the example on the Mozilla site it seems to be simple inheritance.
It means that you don't have to be able to build the tools that you're using to use them.
It's makes programming a lot less stressful when you can abstract things like that away.
Have you ever used the alert() method in JavaScript?
I'm sure that you'd feel a bit overwhelmed if you had to care about how alert communicates with your browser, and how your browser communicates with your display and all the layers in-between.
You don't want to worry about the bezier curves used to render your fonts or how to implement the ok button, or all the other code that makes alert work. All you know is that you can write alert("txt") in JavaScript, and that a dialog box will appear.
walk is implemented in Person. Student isn't allowed to change how it's implemented, it can only override the function completely.
You could design a programming language that allows you to override parts of the parent function rather than the function as whole. This programming language has inheritance but not encapsulation.
Now of course if a child overrides part of a parent function, this means the child and parent implementations are coupled. This is generally considered bad practice. This is why most languages go so far as to enforce encapsulation, but it's not something you absolutely need.
Maybe a good analogy is a plugin mechanism. You can write plugins in different ways: use some event hooking or use clever inheritance but you can also do inline code replacement. Now before you think this is ridiculous, older versions of the popular forum software phpBB actually did this. You can imagine what happens if you install two plugins that might interfere, there's no telling what will happen!

custom class property in ExtJS

What is best practice for naming custom property in ExtJS?
Is it a good idea to precede name with an underline?
Ext.create("Ext.Window,{
height:50,
_custom:"xxx",
_action:"yyyy"
});
another idea is using data_ prefix to mimic html5 custom attribute convention.
I personally don't like anything in a variable name that carries additional syntactic information (Uncle Bob dedicates a whole section to this principle in http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882), not to mention the ugly code it produces (e.g. mywindow._custom).
I would just give your variables descriptive names, and then your code will read better and you shouldn't have to worry about collision with Ext properties (if you were worried about).
I like this much better:
Ext.create("Ext.Window,{
height:50,
customNameOfSomething:"xxx",
actionToPerform:"yyyy"
});
Agreed with others, and will add that the underscore in particular is more or less an accepted standard for private variables in most syntaxes (though Ext JS itself does not use it, and keeps private variables marked as private via comments or undocumented by convention). I definitely would choose some other way to name public configs if you insist on choosing some convention, though I agree with others that it's probably not necessary. I would guess that in most real cases, your custom properties are not going to be so generic as to clash (and if they are, you probably chose poor names for whatever you're adding).
You have to remember that you're designing a custom property that might be used by others. This means that it has to be descriptive of its behavior. That's what is most important. Using an _ is very rare and isn't really natural to developers using the code, so it's gotta be user friendly.
I decided to to use _ as a prefix for custom variables. because:
It prevent any collision
Self-documenting
It's users friendly
It would be better if Sencha used a mechanism to prevent the mixing up.

Disregarding speed and compatibility, why not use only classes and never use IDs in HTML/CSS? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
I use only classes and never use IDs.
Many people like to use IDs for different reasons.
I've seen many questions regarding IDs vs classes on stackoverflow, but no one addressed pure code organization point of view disregarding compatibility and runtime performance.
From code organization point of view, I think that using IDs is bad just like using global variables in Visual Basic code.
One reason is that IDs have to be unique which introduces unnecessary and bad dependency between different independent parts of your code (controlling different parts of HTML DOM tree).
Another reason is that making new class names is actually easier than ID names because with IDs you have to worry about global scope and with class names you need to worry only about uniqueness in local scope, same benefit as with local variables.
Most people will argue that performance of addressing by ID is better than by class and I will agree with that. But as browsers become more advanced with native implementations of CSS addressing from javascript and computers become faster, performance becomes less and less important. So let's disregard it and concentrate only on organization of code in context of current question.
This discussion started here, but my potentially wrong advice generates negative points and became too big to keep in comments, so here I try to convert it into something positive and manageable.
One visible point in favor of IDs is to use them as a tool of rule prioritization because priority of #name is higher than priority of .name.
My response: using IDs to raise priorities is bad hack, it's cleaner and there is more freedom if you use additional root elements inserted between body and other levels of tree, for example priority of body div div span.class1{} is higher than body div span.class1{} is higher than body span.class1{} is higher than span.class1{}. Another tool to use for that purpose is !important.
Some may argue that using more root elements means more difficulties when the page structure changes, but I don't think this is the case because you never have to put anything between body and designated for prioritization divs. Those divs can always stay below body and above all other content.
Another interesting association was brought about pointers and that IDs are not bad because pointers are not bad.
My response: pointers are bad if you hardcode absolute memory address in your code. Using relative pointers is always better (examples: using segments(CS,DS,SS,ES) in 8086 CPU; relative variable and method addresses generated by compilers). If we consider DOM tree as memory and compare using ID to using class then #name represents absolute memory address, but div.tab1 .name represents relative address (relative to div.tab1).
Another supporting point that I've seen for IDs is that elements with IDs are more easily available in javascript as becoming global properties. My response: again, this is like saying that global variables in Visual Basic are more conveniently available. The problem is that you can't keep large enough global (or any other) namespace in order without introducing naming hierarchy like level1_level2_name, which is just a hack to replace one namespace mechanism with another. DOM tree is convenient enough to organize namespaces, why disregard it ?
Namespace simulation inside IDs using underscore is bad because you can't establish naming context and will have to duplicate all paths everywhere in your code. That practically means that you won't be able to use CSS preprocessors that fix inability of CSS to use contexts.
quick answer: its a best practice, if you have only one instance of something and you only want one instance if it, use an ID to define that there should only be one instance of it.
This is like the difference between constant variables vs regular variables. You can use a regular variable to be a constant variable, but its better to define it as such if that is what its intended to be.
It lets fellow programmers (and yourself) know more information about the object.
I agree with you in general: Classes are much cleaner to use; you can create "namespaces" and clean cascades with them; and they can be combined: class='class1 class2'.
IDs still have their place when you're addressing really unique elements on the page, especially when addressing an element that is going to be changed in JavaScript later (e.g. a hidden overlay.)
I look at classes and ids the same way I look at a (programming) class versus an object. An object is one, specific instance of a class. I want all my classes to share a certain number of behaviors, but an individual object may have its own unique properties. CSS classes are for applying properties to broad groups of similar items, ids are for specific items and the specificity hierarchy reflects that.
To invert your question, why use classes at all when you could achieve the same effects with very specific tag selectors? For ease of use, repeatability and clarity of intent.
For me, I like using IDs on HTML elements that are absolutely unique, and classes on things that are possibly non-unique (regardless of whether or not they are).
For example, I would use <div id="header"> because there can only be one header. But I would use <div class="profile"> if there could conceivably be more than one on the page (even if there is only one). This makes the CSS a little easier for me to understand.
"DOM tree is convenient enough to organize namespaces, why disregard it ?"
Because the DOM can change due to AJAX or other javascripty-goodness.
I like #ocdcoder 's constant/variable analogy. Sometimes you want to refer to exactly that particular element. Having to adhere to a strict DOM namespace is a straightjacket that doesn't help maintenance at all, imho.
I think the discussion is incomplete without addressing the underlying reason for using classes and IDs. Saying that either should be used in every situation does not work well generally and historically.
The original purpose of classes was to attach presentation to the document, or introduce style as a separate concern than the structure of the document itself. Please correct me if I am wrong, but I think you are trying to address the problem of attaching semantic information to the elements rather than just style. If that is indeed the case, then classes serve two purposes for us - controlling presentation, and acting and semantic tags. IDs serve the purpose of acting as a unique semantic tag.
XML is highly extensible and allows namespaces which was supposed to be used in XHTML documents to assign meaning to a document as authors saw fit. But there were none in HTML and maybe it was browser incompatibilities or the non ease of use (as Tom mentioned), but most web pages and applications did not take the path of using namespaces in XHTML.
Surely the HTML spec authors saw the glaring need for attaching semantic data to HTML documents and introduced the data- attributes in HTML5 that could be assigned to any element. I would argue that if it's semantic meaning that you are concerned with, this is absolutely the best approach so far, but again browser incompatibilities have always had a major role in determining which spec becomes more commonplace and I hope IE does not have their say this time.
Using an id attribute allows you to link to an element E.g. if you’ve got this HTML:
<div id="log-in">
you can link to the log in section of the page using href="#log-in".
You’re quite right that classes are usually the most convenient and appropriate way to identify page components. But assuming that you’ve got an element that only appears once per page, and assuming you can give it an appropriate name or generate one, I don’t think you’re likely to run into problems using an id for it.

Categories

Resources