问题
Assume that I have a <li id="gen__1002_____46.14_li">
I want to select this li
.
To be able to achieve it, I wrote,
var id="gen__1002_____46.14_li";
document.querySelector("#" + id);
But querySelector returns as;
Failed to execute 'querySelector' on 'Element': '#gen__1002_____46.14' is not a valid selector.
When id
does not include dot
character, it selects correctly.
My question is, how can I select a html dom elements where its id includes .
char. Is there any restriction that id cannot include .
char.
Is there any solution for me rather than removing .'s in ids.
回答1:
You need to escape the dot
$('#thisIs\\.anId') // will select <span id="thisIs.anId">test</span>
And in pure js:
var id="gen__1002_____46.14_li";
id = id.replace(/\./g, '\\\\.'); // escaping dots using regex
document.querySelector("#" + id);
EDIT
If you just want to select element by id, use getElementById()
document.getElementById(id);
来源:https://stackoverflow.com/questions/46399023/cannot-use-query-selector-with-ids-that-includes