HTML: Naming conventions for ID attributes - html

Lately I've been doing a lot of front-end work. Some developers here have been naming their elements things like "divPhotoGalleryContainer" and sometimes I'll just see "galleryContainer."
Is there a good naming convention? Is adding "div" really useful?

The stupid thing is, Hungarian notation like divPhotoGalleryContainer is totally unnecessary with CSS. You can name the ID PhotoGalleryContainer and target it to a <div> element in the CSS:
div#PhotoGalleryContainer {
/* rules */
}
Inside that rule you can usually assume certain properties like display: block, unless you're targeting generic divs somewhere else (kinda bad practice).
There aren't really any specific conventions for naming, just use names that are clear and simple.

I don't think it's particularly useful, but I don't think it's harmful either. Consistency is the most important convention.

The best naming convention is the one that makes sense to the developers/designers involved in the project. Given the two examples in your question, I'd be willing to bet that the "divPhotoGalleryContainer" contains "div" because either: it's referenced in a CSS selector, or some javascript code is looking at it and it's somehow helpful to know what type of element the id is referring to.
The "divPhotoGalleryContainer" convention seems like an HTML-ish flavor of Hungarian notation.

It is good to have a naming convention, because it will make you keep track of your elements and classes, and save you from having to read the html code to find out what element is named what. This will help you both when writing css and javascript. A good naming convention for an id should include:
a way to differentiate closely related elements, such as #passwordContainer from #passwordLabel and #passwordInput
structural names rather than presentational names, for example #main-content rather than #blue-square (as the color might change later). More info here: http://sixrevisions.com/css/css-tips/css-tip-2-structural-naming-convention-in-css/
a way to differentiate similar elements, for example on a page that lists different posts that have the same type of elements, you may name them #postContainer-43 and #postContainer-95 for post number 43 and 95 respectively, and give them the class .post or .postContainer

The most important thing is that you're consistant with whatever method you use.
However, I've always found it helpful to use the hungarian type notation of "divPhotoGalleryContainer", and "txtLastName". It makes it easier to distinguish page elements from other variables, both client and server side.

It's not harmful to add "div" in that case.
As DisgruntledGoat said, hungarian notation can be useless with CSS (that is, unles you don't want to restrict a class to one element type), and Rob's comment is right, you may even change your elements and keep the same classes/IDs, but, it may be helpful to understand the code better, lately.
I always use hungarian notation because I'm used to it. If you're used to something, keep it, as it's easier than changing it. In enviroinments where many coders are writing the same things, unless there is a convention, you may write as you want. However, being over-descriptive is not as bad as being under-descriptive. That said, I vote for comprehensive names for everything including variables, functions, classes, IDs, XML elements, etc. If it gets hard to read, use more/better placed spaces/lines. If it adds more than wanted to the file size, minify it.

Related

Can the id and a class have the same name of an html element?

The CSS allows that I can have a class called “.header”, as well as “.main”, “.footer”, “.aside” and so on... the same for IDs. In theory, I can have 3 selectors with almost the “same” name, like “article”, “.article” and “#article”. And I can do the same with all elements, including, why not, a class called “.html” and an ID called “#body”, etc.
For me, if I see the DOT I know that is a class, and if I see the HASH, I know that is an ID, so for me no confusions, but does it go against the naming conventions?
Yup, you absolutely can. If you’re the only one working on the project, and if this is intuitive to you, go right ahead, no issues.
But when working with a larger team, it generally makes sense to use ids and classes that are little more descriptive in nature. For example, .left-primary-sidebar would tell me a whole lot more about the element than something like .aside, when going through the stylesheet.
Your naming choices are definitely valid.
Naming conventions can differ from company to company, so if you’re the only one working on the repo, you can set your own conventions.

Why should I use "data-" in my attributes or dashes in my tags?

According to many recent HTML specs, when we are using custom attributes (meaning any attributes not defined in the spec), we should prefix them with data-. However, I see no reason to have to do this (unless you require perfectly valid HTML, obviously). Pretty much all current browsers correctly ignore custom attributes, meaning no conflicts except with identically-named attributes from others' code, and we can ignore even this with custom prefixes or something similar (as suggested on the AngularJS directive page). What, if any, other benefits are there? This question has been asked before, at least twice, but both are pretty old.
I forget where I read it, but some guide said custom HTML tags need dashes, and single-word tags aren't valid. First of all, why? Second, should we do this, and why (besides being valid)? Would there be any problem with underscores or camelCase, etc.? Also, conflicts with existing elements shouldn't be a problem, if, like with data attributes, you prefix or suffix them, etc. See the Angular directive page again.
I'm sure all these questions have been asked before, but I'm combining them into one. Is that a good idea (quick, someone ask on Meta)?
The data-* attributes have two advantages:
It is a convention meaning other programmers will understand quickly that it is a custom attribute.
You get a DOM Javascript API for free: HTMLElement.dataset. If you use jQuery, it leverages this to populates the keys and values you find with .data().
The reason for the - in custom element names is for two basic reasons:
It is a quick way for the HTML parser to know it is a custom element instead of a standard element.
You don't run into the issue of a new standard element being added with the same name which would cause conflict if you register a custom Javascript prototype for the DOM element.
Should you use your own custom element name? Right now it is so new that don't expect it to be fully supported. Let's say it does work. You have to balance the issue of the extra complexity with the benefit. If you can get away with a classname, then use a classname. But if you need a whole new element with a custom Javascript DOM prototype for the element, then you may have a valid usage of it.

Is it OK to use unknown HTML tags?

Correct me if I'm mistaken, but AFAIK, unknown HTML tags in markup (i.e. tags not defined in the HTML spec, like say, <foobar>) will eventually be treated as a regular <div> in an HTML 5 browser environment.
I'm thinking: how supportable is this practice? I mean, if I use unknown HTML tags in my markup, what pitfalls can I expect? Will a velociraptor pounce on me within the next few seconds?
The reason I ask is that if these tags defer to <div>, I can potentially use these tags in a more semantic manner than, say, assigning class names that identify modules. Have a look at this article, for example, of a .media class. Now what if instead of writing up that CSS to target .media, I make it target <media> instead? In my opinion, that makes the markup much more readable and maintainable, but I do acknowledge that it's not "correct" HTML.
EDIT
Just to be transparent, I did find this SO question from a few years back. It's been closed as off-topic, but I feel that I have a valid point in my own wording. It's a close duplicate, I admit, but it's from a few years back, so there might have been changes in the general environ of opinions across web developers about the topic.
user1309389 had a very good answer, and I agree with the appeal to the spec. But I disagree with their conclusion, and I think they're wrong about made-up elements leading to "undefined behaviour". I want to propose an alternative way of thinking about it, rooted in how the spec and browsers actually handle made-up elements.
It's 2015, we're on the verge of the CustomElement spec being widely adopted, and polyfills are readily available. Now is a great time to be wondering about "making up your own elements". In the near future, you'll be able to create new elements with your own choice of tag and behaviour in a fully standard and supported way that everyone can love. But until this lands in all browsers, and until the majority of people are using supporting browsers, you can take advantage of the hard work of the Polymer or X-Tags projects to check out the future of custom elements in a nearly-standard and mostly-supported way that quite a few people can love. This is probably the "right thing" to do. But it doesn't answer your question, and frankly I find "just use X" or "don't do X" to be less helpful than "here's how the spec covers this, and here's what browsers do". So, here's what I love.
Against the heartfelt recommendation (and sometimes screaming) of much of the web dev community, I've been working with "made-up" elements for the past year, in all of my production projects, without a polyfill, and I've had no unsolvable issues (yet), and no complaints. How? By relying on the standard behaviour of HTMLUnknownElement, the part of the W3C spec that covers the case of "made-up" elements. If a browser encounters an unrecognized HTML element, there is a well-defined and unambiguous way that it should be handled, and HTMLUnknownElement defines that behaviour, and you can build on top of that. HTMLUnknownElement also has to be powerful and correct enough to "not break the web" when encountering all the tags that are now obsolete, like the <blink> tag. It's not recommended that you use HTMLUnknownElement, but in theory and in practice, there's absolutely no harm in doing so, if you know what you're doing.
So how does HTMLUnknownElement work? It is just an extension of the HTMLElement interface, which is the standard interface underlying all HTML elements. Unlike most other elements however, HTMLUnknownElement doesn't add any special behaviour — you get a raw element, unadorned with any special behaviour nor constraining rules about use. The HTMLDivElement interface works almost exactly the same way, extending HTMLElement and adding almost no additional behaviour. Put simply, making up your own element is almost identical to using a div or span.
What I like about "making-up" elements is the change of mindset. You should use or invent HTML elements based on several factors, ranging from how clear it makes the markup to read, to how the browser and screen readers and search engines parse your code, to how likely your code is to be "correct" by some objective measure. I sparingly use made-up elements, but I use in exactly the way Richard described, to make things more meaningful for the author of the HTML, not just meaningful to a computer service that extracts metadata. When used in a consistent way across a team, there can be a big benefit since made-up elements can concisely express what they're for.
I particularly like using made-up elements to indicate when I will be using JS to define extra behaviour for an element. For instance, if I have an element that will have children added/removed by JS, I will use a made-up element as a clue that this element is subject to special behaviour. By the same token, I don't use a made-up element when a standard element will suffice. You will see <dynamic-list> live happily next to <div> in my code.
Now, about those pesky validators. Yes, using made-up elements isn't "valid" in the sense that it won't pass a "validator". But many commonly used features, patterns, and systems of modern HTML and JS development fail all the W3C validators. The validators aren't the law — the spec is. And the law isn't binding — the implementations in all the browsers are. The utility of validators has been dimishing for years as the flexability of HTML has been increasing, and as browsers have shifted in their relationship to the spec. Validators are great for people who aren't comfortable with HTML and need guidance. But if you're comfortable taking your guidance from the spec and from browser implementations, there's no reason to worry about being flunked by the validator. Certainly, if you follow many of the guidelines offered by Google, Apple, Microsoft, etc, for implementing any experimental features, you'll be working outside the bounds of the validator. This is absolutely an okay thing to do, so long as you're doing it deliberately and you know enough about what you're doing.
Therefore, if you're going to make up your own elements and rely on HTMLUnknownElement, don't just treat it like a wild west. You need to follow a few simple rules.
You have to use a hyphen in the name of your tag. If you do, you are guaranteed to never collide with a future edition of the HTML spec. So never say <wrong>, always say <quite-right>.
Made-up elements can't be self-closing — you have to close them with a closing tag. You can't just say <wrong> or <still-wrong />, you have to say <totally-good></totally-good>.
You have to define a display property for your element in CSS, otherwise the rendering behaviour is undefined.
That's about it. If you do these things, you should be good to use made-up elements in IE9 and up, relying on the safety net of the HTMLUnknownElement. For me, the benefits far, far outweigh the costs, so I've been using this pattern heavily. I run a SaaS site catering to major industrial corporations, and I've had no trouble or complaints thus far. If you have to support older versions of IE, it's wise to stay far away from any "2015" technology or their crude approximations, and stay safely within the well-trodden parts of the spec.
So, in summary, the answer to your question is "yes, if you know what you're doing".
You should always approach HTML as it is defined in its respective specification. "Defining" new tags is a bit of an extreme approach. It might pass a browser check because it implements various failsafes, but there is no guarantee of this. You're entering the land of Undefined Behaviour, at best. Not to mention you will fail validation tests, but you seem to be aware of that.
If you wish to be more semantically expressive in your markup, you can use HTML5 which defines quite a bit of more descriptive tags for describing the structure of your page instead of generic divs which need to be appended ids or classes.
In the end, a short answer: No, it's bad practice, you shouldn't do it and there could be unforeseen problems later on in your development.
No. You will fail validation, you will get random issues cross browser and you WILL be eaten by said dinosaurs. CSS is the answer if you want your page to behave predictably.
Yes We Can.
There is a new spec going on about custom elements/tag - http://w3c.github.io/webcomponents/spec/custom/.
Only issue with this is you have to use js to register your new element
You can read more about this at
https://developers.google.com/web/fundamentals/getting-started/primers/customelements
Rule #1 of browser interoperability is: don't have errors. No matter how many browsers you test in, there are always browsers you can't test, for instance because they don't exist yet.
Also, unknown elements will be treated as <span>, not <div> by most browsers currently.
If it's really source readability(*) you're after, you should look into XML+XSLT.
That way, you can use all the tag names you want, and make them behave in any way you like and you don't have to worry that <media> will be a real element in some future version of HTML.
One good real world example is the element <picture>. If a website ever used <picture> and relied on the notion that this element would have no styles or special content by itself, they are in trouble now!
(*) With XML+XSLT, the readability will be in the XML part, not the XSLT part, obviously.
Generally not recommendable, e.g. IE wont apply css-styles to unknown tags.
All other browsers render unknown tags as inline-Elements (which causes problems with nesting).
I recommend you the following article: http://diveintohtml5.info/ There is a section about unknown tags.
In my case I use a lot of them into my Webkit-powered game GUI system, and everything works.
W3C says:
HTML5 supports unknown tags as inline elements, but it recommends CSS
styling for it.
Here is the source: https://www.w3schools.com/html/html5_browsers.asp
In your example you are talking about <media>, it's could be great but if html6 adds this tag for another element, your code won't be retrocompatible.
The one downside that worries me is what if a custom tag I use now, becomes an official HTML-tag next year or even later?
Therefore how about this: Instead of custom tags use 'div' + a custom CSS-class.
CSS-classes are meant to be custom, it is definitely ok to have your own custom CSS-classes. Your div can then further have any number of CSS-classes associated with it making the semantic machinery even more flexible, you could call it multiple inheritance.
Instead of div you could use span for the same purpose. I would like to use something shorter actually, say p but unfortunately p has its own special behavior of what happens if you don't close it.
But definitely if you go the route of expressing semantics with CSS-classes then it does help to use a tag-name that is as short as possible. I wish there was something shorter than div, say for instance t for 'tag'.
By default, custom elements main parts of many JavaScript-Framwork. It is state of the art in modern javascript.:
var XFoo = document.registerElement('x-foo', {
prototype: Object.create(HTMLElement.prototype)
});
https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements
https://www.html5rocks.com/en/tutorials/webcomponents/customelements/
Is it OK to use unknown HTML tags? If you ask wrong questions, you get allways wrong answers. If you define your unknown tag with javascript as a CustomeElement , your unknown tag is no longer part of the HTML5/HTML-definition.
Yes, you can use unknown tags, if you define the tag in your javascript.
What's wrong with the judicious use of < !-- your stuff here -- >. It worked for scripts back around the time of the Cretaceous–Paleogene boundary. Dinosaurs ceased to be a problem around that time, that is apart from the flying, feathered variety.
It's bad practice and you should not do it. The browser renders it as div as fallback solution in most cases but it's not valid html and therefore never will pass a validity test.

custom attribute vs data-* attribute

I know that data- Attributes is part of HTML 5. It seems to be a good choice to use it to serialize some data in markup. So there are people using data-bind="xxx" . But can I just use bind="xxx". It seems violate schema, of specification, but practically it works in all browser. So my question is, what is the practical reason (not in theory) like performance that I should not use customs attribute just like bind="xxx". I know bind attribute is not reserved attribute.
Thanks
Practically, some browser can implement bind with a totally different meaning.
You're using it for Knockout, but hypothetically the new meaning is different. When you change the inline CSS on one element, it should change it on another element based on a selector in the bind attribute.
There's a reason to respect standards and use private (e.g. data-) or vendor-specific prefixes.
I know this question is old but I had the same question as Fred. I found the answer and I wanted to share it. There is no practical reason not to use an arbitrary attribute name other than what was mentioned in another answer. That is a vendor or browser maker may decide to use the name for something else.
It is however not allowed in the spec, kind-of, while the spec does read that arbitrary attribute names should not be used, there is nothing preventing their use. This is like the US Code for Displaying a flag, it's a set of rules but no way to enforce it.
Contrast this to a rule that is enforced such as a single body tag within an html document, etc. and you can realize that there is nothing enforcing using arbitrary names for attributes.
So what remains is why should you not use arbitrary attribute names? Since it will not pass the W3 html validator, it can be argued that societal pressure may increase to the point that your code will not be acceptable. For example, SEO may suffer, a future employer may not like sloppy code, etc.
I certainly became embarrassed as I make liberal use of arbitrary attribute names to pass data. Something that I will stop immediately. I am now convinced that using the data-* attribute will make my code easier to read, easier to maintain and clean enough for peer review.

Should the “for” attribute always come first in an HTML <label> tag for readability?

In an HTML <label> tag, say there are some custom attributes in the tag and one or more of them alphabetically come before the for attribute. Should the for attribute come first for good style/readability, or does this not matter?
The order of the HTML attributes is irrelevant.
You can try and be consistent for readability, but the DOM parser does not care and once parsed, they do not have any specific order (though in practice they may appear in the order they were assigned).
Personally I would place the for attribute first as other developers looking at your HTML will look for it (and want to see it first).
Up to you/your team, really.
I personally prefer for to always come first, as it’s the thing I’m most likely to want to check for correctness, but if you’ve got custom attributes I guess they might be equally as important.