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

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.

Related

Semantics of class vs ID in reusable templates

I'm working on an online store. I've learned a little PHP and so I'm using a single template file with some conditional includes and such rather than building separate product pages (no database yet though, still learning!).
So I have sections that only exist once per instance of the template (ie once per page) such as section id="product_image". Normally that would be identified with an id. But on a template which is reused a bunch of times do you think class would be more semantically appropriate? (yes I know there's no functional/technical need to switch to class)
An id is singular. There can be only one of the same ID on the page, and an element may only have one ID attribute.
So if your component gets reused, the ID must be different between reuses (Perhaps some sort of database primary key, or something similar).
A class name describes your elements semantically, i.e. this section is a what? widget? calendar? featured articles? That's what a class name is for.
Personally, I always use class names, and only use IDs if I want the link-scroll functionality. Classes, are everything IDs are, but more flexible.
the id and class attributes may be used for structure and functionality, but not semantic meaning, although readability in markup is a great aim.
To infuse your markup with meaning, use semantic elements, and structured data.
The Google Structured Data Testing Tool is a great resource.

Why is it a bad thing to have multiple HTML elements with the same id attribute?

Why is it bad practice to have more than one HTML element with the same id attribute on the same page? I am looking for a way to explain this to someone who is not very familiar with HTML.
I know that the HTML spec requires ids to be unique but that doesn't sound like a convincing reason. Why should I care what someone wrote in some document?
The main reason I can think of is that multiple elements with the same id can cause strange and undefined behavior with Javascript functions such as document.getElementById. I also know that it can cause unexpected behavior with fragment identifiers in URLs. Can anyone think of any other reasons that would make sense to HTML newbies?
Based on your question you already know what w3c has to say about this:
The id attribute specifies a unique id for an HTML element (the id
attribute value must be unique within the HTML document).
The id attribute can be used to point to a style in a style sheet.
The id attribute can also be used by a JavaScript (via the HTML DOM)
to make changes to the HTML element with the specific id.
The point with an id is that it must be unique. It is used to identify an element (or an anything: if two students had the same student id schools would come apart at the seems). It's not like a human name, which needn't be unique. If two elements in an array had the same index, or if two different real numbers were equal... the universe would just fall apart. It's part of the definition of identity.
You should probably use class for what you are trying to do, I think (ps: what are you trying to do?).
Hope this helps!
Why should I care what someone wrote in some document?
You should care because if you are writing HTML, it will be rendered in a browser which was written by someone who did care. W3C created the spec and Google, Mozilla, Microsoft etc... are following it so it is in your interest to follow it as well.
Besides the obvious reason (they are supposed to be unique), you should care because having multiple elements with the same id can break your application.
Let's say you have this markup:
<p id="my_id">One</p>
<p id="my_id">Two</p>
CSS is forgiving, this will color both elements red:
#my_id { color:red; }
..but with JavaScript, this will only style the first one:
document.getElementById('my_id').style.color = 'red';
This is just a simple example. When you're doing anything with JavaScript that relies on ids being unique, your whole application can fall apart. There are questions posted here every day where this is actually happening - something crucial is broken because the developer used duplicate id attributes.
Because if you have multiple HTML elements with the same ID, it is no longer an IDentifier, is it?
Why can't two people have the same social security number?
You basicaly responded to the question. I think that as long as an elemenet can no longer be uniquely identified by the id, than any function that resides on this functionality will break. You can still choose to search elements in an xpath style using the id like you would use a class, but it's cumbersome, error prone and will give you headaches later.
The main reason I can think of is that multiple elements with the same id can cause strange and undefined behavior with Javascript functions such as document.getElementById.
... and XPath expressions, crawlers, scrapers, etc. that rely on ids, but yes, that's exactly it. If they're not convinced, then too bad for them; it will bite them in the end, whether they know it or not (when their website gets visited poorly).
Why should a social security number be unique, or a license plate number? For the same reason any other identifier should be unique. So that it identifies exactly one thing, and you can find that one thing if you have the id.
The main reason I can think of is that multiple elements with the same
id can cause strange and undefined behavior with Javascript functions
such as document.getElementById.
This is exactly the problem. "Undefined behavior" means that one user's browser will behave one way (perhaps get only the first element), another will behave another way (perhaps get only the last element), and another will behave yet another way (perhaps get an array of all elements). The whole idea of programming is to give the computer (that is, the user's browser) exact instructions concerning what you want it to do. When you use ambiguous instructions like non-unique ID attributes, then you get unpredictable results, which is not what a programmer wants.
Why should I care what someone wrote in some document?
W3C specs are not merely "some document"; they are the rules that, if you follow in your coding, you can reasonably expect any browser to obey. Of course, W3C standards are rarely followed exactly by all browsers, but they are the best set of commonly accepted ground rules that exist.
The short answer is that in HTML/JavaScript DOM API you have the getElementById function which returns one element, not a collection. So if you have more than one element with the same id, it would not know which one to pick.
But the question isn't that dumb actually, because there are reasons to want one id that might refer to more than one element in the HTML. For example, a user might make a selection of text and wants to annotate it. You want to show this with a
<span class="Annotation" id="A01">Bla bla bla</span>
If the user selected text that spans multiple paragraphs, then the needs to be broken up into fragments, but all fragments of that selection should be addressable by the same "id".
Note that in the past you could put
<a name="..."/>
elements in your HTML and you could find them with getElementsByName. So this is similar. But unfortunately the HTML specifications have started to deprecate this, which is a bad idea because it leaves an important use case without a simple solution.
Of course with XPath you can do anything use any attribute or even text node as an id. Apparently the XPointer spec allows you to make reference to elements by any XPath expression and use that in URL fragment references as in
http://my.host.com/document.html#xpointer(id('A01'))
or its short version
http://my.host.com/document.html#A01
or, other equivalent XPath expressions:
http://my.host.com/document.html#xpointer(/*/descendant-or-self::*[#id = 'A01'])
and so, one could refer to name attributes
http://my.host.com/document.html#xpointer(/*/descendant-or-self::*[#name = 'A01'])
or whatever you name your attributes
http://my.host.com/document.html#xpointer(/*/descendant-or-self::*[#annotation-id = 'A01'])
Hope this helps.

valid order for attributes of input type tag

I know it's very basic question and hope not so important, but i want to know the answer, please don't suggest only refer links.
we all daily face <input> type tag and their attributes (type, class, id, value, name, size, maxlength, tabindex etc..), I just want to know
is there any specific order required for attributes in <input> tag or can we use any order?
if there an order then what is it?
Already been answered, but my full and expanded answer is:
There is no predefined order for the attributes in terms of passing w3c validation... it's completely up to you.
However, you should introduce your own standard and stick to it.
If there are multiple coders working on the application they should all stick to the same standard.
If you are a team leader, web-dev business owner, manager, etc, it is your responsibility to encourage (and enforce) a culture that uses this standard.
When doing code reviews the attribute order should be checked, and anything that fails you should make the coder responsible fix it up... they'll only muck it up once or twice if they know they'll have to rewrite their code!!!
And why all this fuss and bother over attribute order?
This will increase code development and debugging speed.
It makes code more readable
It encourages the coders (or you) to pay attention to the little details
It helps to fosters an environment of "accountability for your own code"
My personal preference is:
type (so you can instantly see what it is)
id
class (I like to keep 2 and 3 together as they are the most common js/jQuery selectors)
name
value (I like to keep 4 and 5 next to each other so you can quickly reference what input it is and it's value).
All others (like checked, max-size, etc)
style
tabindex (I like 7 and 8 to be at the end as it's "non-relevant", in terms of the actual functionality, they are more styling/usability stuff, keep 'em out of the way!
You can use any sequence
Here's code guide from Mark Otto
General attribute order guide
He gives a general guideline to HTML CSS and JS although nothing specific about input tags alone. I think it's a good read.
The order of attributes in HTML elements doesn't matter at all. You can write the attributes in any order you like.
my preference is: id, name, type, class, attributes (like selected, checked), value

HTML: Naming conventions for ID attributes

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.

Is it code-smelly to have empty classes in the middle of a class hierarchy?

I sometimes end up with a class hierarchy where I have an abstract base class with some common functionality and a couple of implementing classes that fall into two (rarely more) groups which I want to treat differently in some cases. An example would be an abstract tree node class and different branch and leaf implementations where I want to distinguish branches and leaves at some point.
These intermediate classes are then only used for "is-a" statements in flow control and they don't contain any code, although I have had cases where they "grew" some code later.
Does that seem smelly to you? In my tree example, one alternative would be to add isLeaf() / isBranch() abstract methods to the base class and implement those on the intermediate classes, but that didn't seem to be any better to me, really, unless I'd mean to have classes that could be multiple things at once.
To me, using "is-a" tests in flow control is just as smelly as using switch/case. In a good OO design, neither is needed.
Yes, deep inheritance hierarchies are a code smell anyway.
Yup, definitely a code smell -- don't code these empty classes unless you're ready to write that code into it. Think YAGNI (you aint gonna need it) -- don't do it unless you need it already.
Also, have you considered cases wherein these classes are only there to provide abstract methods, or to group them based on capabilities in terms of methods or properties?
If that's the case, maybe what you really need are interfaces, not additional abstract classes?
In general, empty classes are a code smell.
I agree your isLeaf or isBranch methods are a correct alternative.
They add information about the objects , which is helpful.
(This is because, on the super class, you can't express that subclasses are "either leaf or branch").
The two methods with opposite results might also be considered as code duplication.
You could use only one... But I would recommend return an enumerated value LEAF or BRANCH.
A class that doesn't contain any code is definitely a code-smell....
Seems alright to me, if you're going to put new functionality in later.
But if not, an enum is generally used here.
-- Edit
Though I must agree with Ber, that you shouldn't generally be using 'is-a' anyway.