Cannot use query selector with id's that includes “.” [duplicate]

佐手、 提交于 2019-12-13 10:33:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!