Chrome console escapes backslashes of a CSS selector

After I execute in chrome console:

document.querySelector("#n-\.D7\.A2\.D7\.A8\.D7\.99\.D7\.9B\.D7\.AA-\.D7\.AA\.D7\.A4\.D7\.A8\.D7\.99\.D7\.98-\.D7\.96\.D7\.94").style.display = "none";

I get:

VM1038:1 Uncaught DOMException:
Failed to execute ‘querySelector’ on ‘Document’: ‘#n-.D7.93.D7.A4.D7.99.D7.9D-.D7.9E.D7.99.D7.95.D7.97.D7.93.D7.99.D7.9D > a’
is not a valid selector.
at <anonymous>:1:10

I get the impression that this is due to ignoring the backslashes in the executed code.
I don’t want to escape each backslash individually.
is there a way to escape all backslashes globally?

Hi,

Why would you need to escape anything? What is the element you are trying to select?

Hi, the element I want to select is:

#n-\.D7\.A2\.D7\.A8\.D7\.99\.D7\.9B\.D7\.AA-\.D7\.AA\.D7\.A4\.D7\.A8\.D7\.99\.D7\.98-\.D7\.96\.D7\.94")

When I select it with querySelector() and try to set its display to none, I get the above error indicating that the backslashes were ignored, hence selection failed.

So you have an element like this?

<div id="n-\.D7\.A2\.D7\.A8\.D7\.99\.D7\.9B\.D7\.AA-\.D7\.AA\.D7\.A4\.D7\.A8\.D7\.99\.D7\.98-\.D7\.96\.D7\.94">
  ...
</div>

Yes. It is created by a CMS (MediaWiki) and I prefer to work with as is, at least now.

You’ll have to escape each backslash 4 times and each dot twice. E.g.

<div id="n-\.D7\.A2">
  ...
</div>

const el = document.querySelector('#n-\\\\\\.D7\\\\\\.A2')
console.log(el);

You could try building the selector programatically.

.replace(/\./g,"\\\\\\\\\\\\.")

"#n-\.D7\.A2\.D7\.A8\.D7\.99\.D7\.9B\.D7\.AA-\.D7\.AA\.D7\.A4\.D7\.A8\.D7\.99\.D7\.98-\.D7\.96\.D7\.94".replace(/\./g,"\\\\\\\\\\\\.")
"#n-\\\\\\.D7\\\\\\.A2\\\\\\.D7\\\\\\.A8\\\\\\.D7\\\\\\.99\\\\\\.D7\\\\\\.9B\\\\\\.D7\\\\\\.AA-\\\\\\.D7\\\\\\.AA\\\\\\.D7\\\\\\.A4\\\\\\.D7\\\\\\.A8\\\\\\.D7\\\\\\.99\\\\\\.D7\\\\\\.98-\\\\\\.D7\\\\\\.96\\\\\\.D7\\\\\\.94"

Though the back of my head’s telling me that after the replace, you wouldnt actually need that many slashes, because it gets passed as a preprocessed string.

Yeah, I would definitely look at a different way to select things. Maybe something like the element starts with selector would yield results.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.