How to understand escaping characters in document.queryselector?

Viewed 535

Am looking at https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector#Escaping_special_characters

and I can't understand this section:

// "#fooar" (\b is the backspace control character)
console.log('#foo\bar');
 // Does not match anything
document.querySelector('#foo\bar');

console.log('#foo\\bar'); // "#foo\bar"
console.log('#foo\\\\bar'); // "#foo\\bar"
document.querySelector('#foo\\\\bar');
<div id="foo\bar"></div>
<div id="foo:bar"></div>

I'm a JavaScript beginner and don't understand why the 4 slashes, I found another similar question but I didn't understand the answers.

I tried to run document.getElementById on "foo\bar" and it works ok with 2 slashes which makes sense to me as you need an extra backslash to escape the first backslash but why an extra 3 when using querySelector?

I have looked at similar posts on here but the answers are not clear for me, I'm looking for a simple breakdown explanation of what's happening here and what the difference is between how getelementbyid works which I do understand (double backslash) and queryselector (which uses 4).

1 Answers

According to the MDN Web Docs, about litteral Strings:

Besides regular, printable characters, special characters can be encoded using escape notation.

  • \\ -> \

Now, about Document.querySelector method:

To match against an ID or selectors that do not follow standard CSS syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash ("\"). As the backslash is also an escape character in JavaScript, if you are entering a literal string, you must escape it twice (once for the JavaScript string, and another time for querySelector()):

No such things is required for Document.getElementById (no explanation is given, maybe it's for legacy reason). Now, back to our question:

Consider the process as a two-pass formatting, let's view them backwards:

  1. You need to send to querySelector a backslash. To fit the requirement of querySelector, You need to escape it once : "#foo\\bar".
  2. If you want to represent a backslash in a Javascript String, you need to escape it. Let's escape each backslash; we get "#foo\\\\bar"
Related