Is it bad practice to put numbers as id in HTML elements? If so, why?

Asked

Viewed 1,595 times

12

I have a loop printing HTML elements, for example:

for($i = 0; $i < 3; $i++){ echo "<div id='$i'>$i</div>"; }

Is it bad practice to put numbers as id in HTML elements? If yes why?

  • 1

    The id should be unique. If you guarantee this unity, I see no problem with that. They should also be mnemonic, easy to remember. If you can organize yourself with numbers, I don’t see any problems either. I am unable to organize myself only with numbers, I prefer textual identifier

  • So in my case, I’m going to identify elements by the numeral and insert into a table the contents of that element, as I have N elements I’m going to use a repeating structure. I also prefer a text-type indetifier.

  • 2

    How about concatenating? How id='info_$i'?

  • For everyone who is arriving now: yes, it is a bad practice, but no, it is not forbidden. A digit is an alpha characternumerical.

  • 1

    From HTML 5 to W3C allows the use of ids numerical, see first note of the recommendation. The specification WHATWG also allows this. But still the recommendation is that the id start with a letter, to maintain HTML 4 compatibility.

3 answers

11

As @Renan said, a number is an alphanumeric character. I agree that using only numbers is bad practice, but it doesn’t go against what the W3C establishes.

Really "there is no technical problem", but how did you ask about "malpractice", yes there is a problem.

See that in the section 3.2, HTML5 elements, about the ID attribute, it is said:

The id attribute specifies its element’s Unique Identifier (ID). The value must be Unique amongst all the Ids in the element’s home subtree and must contain at least one Character. The value must not contain any space characters.

That in free translation would be:

The id attribute specifies the unique identifier (ID) of the element. The value must be unique between all ID’s in the element source subtree and must contain at least one character. The value shall not contain any space character.

This establishes the standards for using the ID:

  • Shall not contain any space character;
  • Should be unique;
  • Must contain at least one character;

And a toast should be mnemonic, easy to remember. I’m also unable to organize only with numbers, I prefer textual identifiers.

Very hard to remember, the position of a table only with numbers, for example <div id='12'></div> to represent row 1 and column 2. It would be much simpler <div id='l1c2'></div> and/or similar derivations.

The unique identifier of an element can be used for various purposes, mainly as a way to link to specific parts of a document using fragment identifiers, as a way to segment an element when it is using scripts and as a way to model an element specific to CSS.

I particularly see much more practicality in alphanumeric characters. The amount of times I would lose looking for the number in an HTML file with Javascript, CSS and other technologies, would be impossible, while with alphanumeric characters or only textual would bring much more practicality. Imagine looking for a div with ID number 1, and search for a div with ID div-da-esquerda. The chance of repetition, which the text editor can find, is much smaller and unlikely in elements with non-numerical ID.

As a recommendation, whenever possible, try to use nomenclature that reflects the id content attribute. And avoid using unknown and/or strange names. It’s not because I can create variables with random names like:

String qualquercoisaquequisercolocaraleatoriamente = 'qualquervalor';

I’m gonna raise them like this. Programmers write code, but good programmers write code that is understandable by both humans and machines.

  • 4

    A number is an alpha characternumerical. I agree that using only numbers is bad practice, but it does not go against what the W3C establishes.

  • The standard says must contain at least one Character. I understand that she doesn’t explicitly say, as you say, but as the AP asked about "malpractice", I found it interesting to highlight the reasons that this "hurts the standard".

  • @Renan still believe that if it were the case the W3C would have put as alphanumeric Character. And not just one Character.

  • 4

    In this case, I must agree with @Renen, character is being used in the broad sense in this case. Of any sort, +1 by id='l1c2'

  • 2

    I think "character" is any character, including numbers. So much so that this same document mentions "U+000A LINE FEED (LF) characters" or "each U+002D HYPHEN-MINUS Character (-)". If it were only letters and numbers they would mention, as they did in other excerpts " Character in the range U+0041 to U+005A", i.e., specifying which characters are.

10


There really is no technical problem using only numbers as selectors in the CSS since you ensure that you will never repeat the ID selectors for different elements. Now, imagine a more complex setting, with numerous HTML elements and numerous selectors to "decorate", after all, you can’t count on remembering all the head selectors when you’re developing. So there are some Patterns design and best practices that are highly recommended for your development process to flow and end up being faster, after all, time is money.

I found this article quite interesting about naming Ids and classes in CSS to facilitate development. There is also this link of a Google style guide, which is quite interesting too.

As for Patterns design, I recommend this book which addresses different development Patterns design for HTML5 and CSS.

  • Truth @Isac had really forgotten this detail. Thank you for your addendum!

  • 3

    A number is still a character. So we say alphanumerical.

  • 1

    The answer is correct, there is no need for negatives. The W3C rule states only that must contain at least one single character and be distinct from other characters id, thus using numbers may not be a good practice speaking semantics, but there is nothing to prevent this other than the developer himself.

  • 1

    I apologize to everyone for the way I interpreted the rule. There is in fact no impediment to Html5 in using id only numerical, and yes only in html4. If you can remove the -1 data in this reply for this reason I thank you.

  • 1

    @Isac from me you have +1, your answer is good.

5

My answer tends to detach from the HTML context, although it is fully applicable. This is because the existing answers already answer this side of the question. I want to address a broader concept.


One of the most important things (and for most it is not so important) that the book "Clean Code: A Handbook of Agile Software Craftsmanship", by Robert C. Martin, addresses is the nomenclature you give for variables, classes and everything else. This you find in chapter 2, "Meaningful Names".

Be expressive and self-explanatory when naming. But why?

The mentality you have to have when programming is that you’re programming for other people to read your code later. One day that stretch of skunk that even you don’t understand will have to be maintained by someone else. The funny thing is that this someone might be both you in a few months' time and a whole team.

The only valid measurement of code quality: WTFs/minute

The only valid code quality measure: Wtfs per minute

To prove what I’m saying, answer me: what does this code do?

for (int j = 0; j < 34; j++) {
    s += (t[j] * 4) / 5;
}

From the code review room:

"WTF?! WTF?! WTF?!"

You probably don’t even know the reviewers! It’s not just because you don’t know what project it is from, or the programming language. It is because the variables are badly written. See the same code with a little more expressiveness and self-explanatory:

const int realDaysPerIdealDay = 4;
const int WORK_DAYS_PER_WEEK = 5;
int sum = 0;
for (int j = 0; j < NUMBER_OF_TASKS; j++) {
    int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;
    int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK);
    sum += realTaskWeeks;
}

Not only are variables better named but those numbers that were fixed and doing calculations were moved to constants. This is to let the code explain itself and not need thousands of comments explaining what it does.

Writing meaningful names

It is not an easy task. The fragments below were taken from the book I quoted at the beginning.

The names must reveal their intentions

Only how you name a function, class or variable can you convey to those who read what it does, how it does, why it does and how it is used.

int tmm; // não use
int tempoMedioMinutos; // use
int tempoMedioEmMinutos; // use

Avoid disinformation

For languages that are weakly typed, like Javascript, this can cause a problem. Why would you name a variable of listaContas if she’s not even a list?

Make distinctions with meaning

Sometimes we use words that add nothing when naming a class.

What you tell me about classes Produto, ProdutoInfo and ProdutoData? Are they different? In what? In that case, go back to "The names must relegate their intentions" and rewrite with meaning.

Use searching names

Remember back there I mentioned the constant after I asked you what that code meant? It’s the same case.

if (visitor.CountryCode == '1237') { 
    visitor.redirectTo('/al');
}

against:

const BLOCKED_COUNTRY_CODE = '1237';
if (visitor.CountryCode = BLOCKED_COUNTRY_CODE) {
    visitor.redirectTo('/al');
}

We were able to give meaning to a value that was coupled in a fixed, constant way. So it is easy to read and find too.

More...

Here I talked about the little bit the book covers. It’s a more than recommended reading for programmers. Good reading :)

Beyond the Clean Code

It’s not just the book that addresses this. A PEP 20, by Python, commonly "The Zen of Python", which can be applied not only to Python, says that:

  1. Readability of account code
  2. Explicit is better than implicit

Of the 19 points that this PEP talks about, these two are very applicable in this context.

  • Prefer readability, write to others or the future-you understand
  • Be explicit when naming members and using the characteristics of a language.

From the premises raised here, you can infer to name yourself:

<div id='1'>1</div>
<div id='2'>2</div>
<div id='3'>3</div>

is a bad practice or not. You may even conclude if $i = 0 is good or not.

Now whenever programming, ask yourself: how many Wtfs per minute would you receive in code review?

Has a video of Filipe Deschamps on the importance of names and the Clean Code. Actually there are a number of videos about Clean Code. Said he:

If we think that taking out the syntax of a code, basically what remains is a lot of name behind another name, calling another name and so on.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.