Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always bad practice to start an ID with a number? (CSS)

Tags:

html

jquery

css

php

In my project I have submissions and comments, each with an ID. Currently the ID's are just numeric and correspond to their database ID's. Everything is working fine but when I run it through the W3 validator I get the error:

value of attribute "id" invalid: "1" cannot start a name

I suppose instead that I could just precede all ids with some sort of string but then whenever I was using or manipulating the id in JQuery or PHP I have to do a id.replace('string', '') before using it. This seems rather cumbersome. Any advice?

like image 846
John Smith Avatar asked Mar 20 '11 04:03

John Smith


People also ask

Can CSS ID start with a number?

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.

Is it bad to use ID for CSS?

It is not advisable to use IDs as CSS selectors because if another element in the page uses the same/similar style, you would have to write the same CSS again. Even if you don't have more than one element with that style right now, it might come later. Hence it is always advisable to use class.

Can ID in HTML start with number?

Note: The id name is case sensitive! Note: The id name must contain at least one character, cannot start with a number, and must not contain whitespaces (spaces, tabs, etc.).

Can we give ID as number in HTML?

From the HTML 4 specification: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").


1 Answers

Yes, using numbers as HTML element IDs is bad practice.

  1. It violates W3C specification.
    You noted this in your question, and it is true for every HTML specification except HTML5

  2. It is detrimental to SEO.
    Search-engine optimized HTML element IDs SHOULD reflect the content of the identified element. Check out How To Compose HTML ID and Class Names like a Rockstar by Meitar Moscovitz. It provides a good overview of this concept.

  3. There can be server-side scripting issues.
    Back when I first started programming in ASP classic, I had to access submitted form fields by a syntax like Request.Form("some_id"). However, if I did Request.Form(1) it would return the value of the second field in the form collection, instead of the element with an Id equal to 1. This is a pretty standard behavior for working with collections. Its also similar with javascript, and could make your client side scripting more complicated to maintain as well.

like image 193
smartcaveman Avatar answered Sep 22 '22 18:09

smartcaveman