Cannot use query selector with id's that inclu

2019-09-19 19:27发布

This question already has an answer here:

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条回答
劳资没心,怎么记你
2楼-- · 2019-09-19 20:08

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);
查看更多
登录 后发表回答