-1

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.

mmu36478
  • 1,295
  • 4
  • 19
  • 40
  • Try like `$('#gen__1002_____46\\.14_li');` – Znaneswar Sep 25 '17 at 06:43
  • I have already tried it, But this returns as; Uncaught DOMException: Failed to execute 'querySelector' on 'Element': '#gen__1002_____46\\.14' is not a valid selector. – mmu36478 Sep 25 '17 at 07:03

1 Answers1

0

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);
mrid
  • 5,782
  • 5
  • 28
  • 71