Does querySelector fail with CSS.escape? Safely finding IDs starting with colons, periods, or numbers

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About this article
This article was created using an automated generation workflow leveraging generative AI. We reviewed the official specifications and explanations for CSS.escape and querySelector, and prepared static learning materials featuring fictitious ticket IDs. While we verified logic and input validation using a pseudo-DOM in Node.js, rendering and operations in actual browsers, deployment to GitHub Pages, and display in WordPress have not been verified.

Verification Status: 📘 Specification and logic verified / Browser interaction unverified

Does querySelector fail with CSS.escape? Safely finding IDs starting with colons, periods, or numbers

"The target is not found even though the button was clicked" or "An exception occurs in querySelector even though the ID is known." These phenomena occur simply because ticket numbers on list screens or identifiers from external services contain colons or periods. The cause is that HTML IDs and CSS selectors follow different grammars. In this article, we will experience these differences through four fictitious examples and organize the appropriate usage and precautions.

Capabilities and Testing Environment

ItemContent
TargetBrowsers supporting CSS.escape and querySelector, HTML/CSS/JavaScript
RequirementsA browser and local static HTML/JavaScript files. No registration for external services required
SubjectFour fictitious ticket IDs. Real customer numbers or internal IDs are not required
Verified13 validation tests using a pseudo-root in Node.js 22.16.0
UnverifiedActual browser CSS parser and screen operations, Pages deployment, WordPress display

Open live demo (accessibility and interaction unverified)

Complete set of HTML, JavaScript, README, and tests (pinned commit)

If the link cannot be opened in the browser, please place docs/demos/css-escape-selector-lab/ and index.html located in app.js of the same commit on GitHub into the same folder, and open the HTML locally. The existence of a public URL and the fact that the screen operates normally are different things. The explanation of results represents expected values based on specifications, and does not claim to be actual browser measurements here.

Try first: Changing just one character changes the result

Enter ticket:01 into the "Target ID" field on the screen and search. Since "colon-included ID / ticket:01" is present in the prepared list, a compatible browser is expected to display "Found". Even if the input field is edited, the display will not change until the search button is pressed. This allows for separate observation of input modification and search execution.

Next, enter ticket.02、123-start、a[b] one by one. The target is the same list of four items. Because only characteristics such as colons, periods, leading numbers, and square brackets are changed, it is easy to track which input changed the search result. Finally, entering missing results in no matching items, so it is expected to show "No match". Leaving it blank also does not generate an invalid selector and results in "No match".

Search IDExpected ResultPoints to Note
ticket:01Colon-included ID is found:Prevent misunderstanding as a pseudo-class
ticket.02Period-included ID is found.Prevent misunderstanding as a class specification
123-startID starting with a number is foundAbsorbing leading character constraints as a CSS identifier
a[b]IDs with square brackets are foundDo not confuse with attribute selectors
missing or blankNo matchDistinguish between not found states and implementation errors

What is surprising about this comparison is that even the same ID can be used on the HTML side, but may not be written as-is for CSS #ID. Before concluding that the data is corrupted due to special characters in the ID, you need to question the syntax used for the search.

Why simply concatenating strings like # is not enough

document.querySelector() or passed to an element's querySelector() are CSS selectors, not the ID itself. Simply writing "#" + id will cause colons to be interpreted as pseudo-classes, periods as class specifiers, and square brackets as the start of attribute selectors. Values starting with numbers also require a different writing format as CSS identifiers. There are cases where it simply is not found, and cases where it results in an exception due to a syntax error; the same failure does not necessarily occur for every character.

On the other hand, CSS.escape(id) transforms the ID into a form that can be safely embedded as a CSS identifier. For example, the colon in 'ticket:01' is written in a way that allows it to be recognized as part of the ID rather than a CSS selector symbol. Even if the converted string looks complex, it is not a process that rewrites the target ID itself.The key point is to keep the displayed value as it is and change only the search syntax.

The core processing of the tutorial is as follows. escapeFn by allowing the browser's CSS.escape to be passed, the logic tests using the pseudo-DOM and the execution on the screen side are separated.

function selectById(root, id, escapeFn) {
  if (typeof id !== "string" || id.length > 80) {
    throw new RangeError("IDは80文字以内の文字列にしてください");
  }
  if (id.length === 0) return null;
  if (typeof escapeFn !== "function") {
    throw new TypeError("CSS.escapeが使えません");
  }
  return root.querySelector("#" + escapeFn(id));
}

The first condition is the demo-specific input limit. The 80-character limit is not a restriction of CSS.escape itself. Without the following check for an empty string, "#" would result in an invalid selector, and the search process could throw an exception. After verifying the existence of the API, the search is executed for the first time on the last line. Since the search target is limited to the list elements root within the screen, the intent of this example is not to search for unrelated elements across the entire page.

Visualizing the separation point between the ID and the selector

The following diagram shows only the position where escaping is performed. Note that instead of changing the input ID value, the conversion is applied immediately before constructing the selector string. The case where the search result is null and the case of a syntax error are handled via separate code paths.

flowchart TD
    A[検索したいID] --> B{空文字か}
    B -->|はい| N[一致なし]
    B -->|いいえ| C[CSS.escapeで識別子へ変換]
    C --> D[先頭に # を付ける]
    D --> E[querySelectorで検索]
    E --> F{対象はあるか}
    F -->|はい| G[対象の文字を表示]
    F -->|いいえ| N

The diagram does not represent DOM creation, modification, or persistence, but rather the processing order of at which stage the search key is converted. In actual tutorials, when browsers do not support CSS.escape or when the input is too long, exceptions are caught and the reason is displayed on the screen.

Changing only one condition to compare with an alternative approach

The methods discussed so far apply when there is a need to "search using a CSS selector." However, if the goal is simply to specify an ID within the page, there is also the option to use document.getElementById(id). Because this method does not parse the input as a CSS selector but rather searches for it as an ID string, there is no need to worry about selector-specific escaping. The tutorial uses root.querySelector() because it searches only the descendants of the list element, but determining beforehand which method is appropriate is easier if the search scope spans the entire document.

When making comparisons, keep the search target constant and change only the search method. For example, when searching for ticket:01, distinguish between passing the raw CSS #ticket:01, passing it through CSS.escape, and searching the entire document by ID. Even if a raw selector search fails, it does not necessarily mean that the ID itself does not exist. Furthermore, in pages where IDs are duplicated, the first matching element may be selected; thus, adopting any of these methods does not automatically fix poorly structured HTML with duplicate IDs.

Another boundary condition is whitespace. Including ASCII whitespace in an HTML ID attribute value is not compliant with the specification. The example a b from the previous version of the tutorial was inappropriate for introducing special characters, so it has been replaced with a[b] in this version. Even if browsers handle invalid IDs in certain ways, that does not justify recommending such practices in production interfaces.

Troubleshooting when search fails

First, check the screen state. If "No match" is displayed, it is possible that no element corresponds to the entered ID, or the search range differs. Check leading and trailing spaces, uppercase and lowercase letters, hyphens, and colons character by character. Since automatically normalizing the input string here might treat originally distinct identifiers as identical, the demo does not auto-correct the input.

If "Cannot search" is displayed, check for causes such as lack of API support, input values outside the function's range, or exceptions thrown while constructing the CSS selector. Checking the error details in the browser's developer tools helps avoid confusing non-detections with syntax exceptions. If the screen is completely unresponsive, first app.js and index.html are in the same folder and that the script is loaded. Merely being able to display the HTML does not mean JavaScript has executed.

If the search result points to the "wrong ticket," this is an issue that cannot be resolved by CSS.escape alone. Check whether IDs are duplicated, whether this immediately follows a dynamic redraw of the list, or whether the search target root is the expected list.querySelector() is not designed to return all multiple matches. If you need to handle multiple items, it is safer to design a separate selection API rather than forcibly fitting it into a single ID search.

How to use them properly in operations

In management screens where external service ticket numbers are used as DOM IDs, and those numbers contain colons or periods, the conventional "#" + 番号 approach may make searches appear to suddenly fail. At that point, what you really need to verify is not only the validity of the data, but also which grammar the data string was passed to. It is practical to use CSS.escape only when constructing CSS selectors, while simultaneously verifying the target scope and ID uniqueness.

On the other hand, when designing a new screen from scratch, you can also choose not to use identifiers containing special symbols as HTML IDs. Methods include separating business codes into data-* attributes, separating display text from internal keys, or using getElementById for simple ID lookups. CSS.escape is a conversion for CSS selectors, and it is not a substitute for XSS countermeasures, SQL countermeasures, or authorization checks. The tutorial uses textContent to display results, making sure that external strings are not interpreted as HTML.

This Node.js test examines string validation, passing data to the escape function, and checks branches for undetected inputs, empty strings, exceeded lengths, and unsupported cases. It does not prove how an actual browser searches for ticket:01 or similar patterns and renders them on the screen. For initial implementation, test with dummy data and a local HTML file, and verify your target browsers, DOM generation order, duplicate IDs, and accessibility before expanding to production screens.

Official and Primary Sources

GitHub Sample

Document information

Article title
Does querySelector fail with CSS.escape? Safely finding IDs starting with colons, periods, or numbers
Published
Updated
Source
https://papanda925.com/?p=18724&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL