不能使用包含“。”的id的查询选择器。

时间:2017-09-25 06:40:35

标签: javascript html jquery-selectors selector

假设我有<li id="gen__1002_____46.14_li">

我想选择此li

为了能够实现它,我写道,

var id="gen__1002_____46.14_li";
document.querySelector("#" + id);

但是querySelector返回为;

Failed to execute 'querySelector' on 'Element': '#gen__1002_____46.14' is not a valid selector.

id不包含dot字符时,它会正确选择。

我的问题是,如何选择html dom元素,其id包含. char。是否存在id不能包含. char的限制。

对我来说是否有任何解决方案,而不是删除ids中的。

1 个答案:

答案 0 :(得分:0)

你需要逃避点

$('#thisIs\\.anId') // will select <span id="thisIs.anId">test</span>

纯粹的js:

var id="gen__1002_____46.14_li";
id = id.replace(/\./g, '\\\\.'); // escaping dots using regex
document.querySelector("#" + id);

修改

如果您只想按ID选择元素,请使用getElementById()

document.getElementById(id);