Home >Web Front-end >JS Tutorial >The difference between js querySelector and getElementById to get elements by id_javascript skills

The difference between js querySelector and getElementById to get elements by id_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:54:071103browse

This was discovered by sina colleague xiaoniu, as follows

Copy the code The code is as follows:








<script> <br>var str = '02E503E2A1C011CFC85B7B701A0677EC0 900000000000001'; <br>function bySelector(id) { <br>return document.querySelector( '#' id); <br>} <br>function byId(id) { <br>return document.getElementById(id); <br>} <br><br>alert(bySelector(str)); <br>alert(byId(str)); <br></script>



Two functions bySelector and byId pass respectively querySelector and getElementById get the element.

There is an element with the id "02E503E2A1C011CFC85B7B701A0677EC0900000000000001" on the page.

Result: All browsers that support querySelector cannot obtain it through bySelector (an error is reported), but it can be obtained through getElementById.

I began to suspect that the querySelector could not be obtained because the id string was too long. The real reason is that querySelector is implemented according to CSS specifications, that is, CSS identifiers cannot start with numbers.

W3 wrote
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. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B&W?" or "B26 W3F".
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