Home  >  Article  >  Web Front-end  >  Can IDs in HTML Start with or Consist Only of Numbers?

Can IDs in HTML Start with or Consist Only of Numbers?

DDD
DDDOriginal
2024-11-12 19:50:02809browse

Can IDs in HTML Start with or Consist Only of Numbers?

Can IDs Contain Only Digits?

Can you create an element with an id that starts with or is completely comprised of numbers?

Yes, you can. However, using such IDs with CSS selectors can be challenging.

ID Validation:

HTML5 allows IDs that consist solely of digits, as long as they're not spaces. Browsers have always been flexible with this, even before the HTML5 specification.

CSS Selectors:

While you can use numeric IDs, it becomes cumbersome in CSS selectors. IDs starting with digits cannot be written literally; you must escape them using backslashes (e.g., #12 becomes #3132 in CSS).

Recommendation:

If you plan to use these IDs with CSS selectors, it's advisable to start them with letters for convenience.

Examples:

Here's an example using a div with id "12":

<div>
# {
    background: #0bf;
}
document.getElementById("12").style.border = "2px solid black";

This works in major browsers, as demonstrated in the live example below:

[Live Example](https://jsfiddle.net/e0xs9L06/)

The above is the detailed content of Can IDs in HTML Start with or Consist Only of Numbers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn