-1

I want to write the code like that document.querySelector('#foo\bar'); and it does not work

    <div id="foo\bar"></div>
    <div id="foo:bar"></div>

<script>

  document.querySelector('#foo\\\\bar'); // Match the first div
  document.querySelector('#foo\\:bar');  // Match the second div
</script>

1 Answers1

2

JavaScript string syntax uses the backslash as an escaping mechanism for special characters. In order to get a string to end up with a single backslash, you have to double it.

Then, CSS selector syntax for querySelector() also uses the backslash character as a special escape sequence start, and so it's the same thing all over again.

Thus parsing the string reduces the backslashes to two, and then interpreting the selector results in querySelector() looking for just a single backslash.

Pointy
  • 405,095
  • 59
  • 585
  • 614