Sid
Sid

Reputation: 4502

How to escape correctly querySelector() characters

I have iframe with id = google_ops_iframe_/15465462/cor.it_320x320_domestic_mobile_OF_0__container

How to escape this id's characters to be able to select this element with querySelector()?

I've tried following with no luck:

var elem = document.querySelector("#google\\_ops\\_iframe\\_\\/15465462\\/cor\\.it\\_320x320\\_domestic\\_mobile\\_OF\\_0\\_\\_container");

Upvotes: 2

Views: 1956

Answers (1)

Magus
Magus

Reputation: 15104

I start with the obvious, but this line work:

document.getElementById('google_ops_iframe_/15465462/cor.it_320x320_domestic_mobile_OF_0__container');

You don't have to escape characters when using getElementById.

But if you really have to use querySelector, the problem is with / and . characters. So your selector should be #google_ops_iframe_\\/15465462\\/cor\\.it_320x320_domestic_mobile_OF_0__container

Here a working example:

console.log(document.querySelector('#google_ops_iframe_\\/15465462\\/cor\\.it_320x320_domestic_mobile_OF_0__container'));
<iframe id="google_ops_iframe_/15465462/cor.it_320x320_domestic_mobile_OF_0__container"></iframe>

Upvotes: 6

Related Questions