Home > Web Front-end > JS Tutorial > body text

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

DDD
Release: 2024-11-12 19:50:02
Original
777 people have browsed it

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>
Copy after login
# {
    background: #0bf;
}
Copy after login
document.getElementById("12").style.border = "2px solid black";
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template