0
<h2 id="example/123">A heading</h2>

<script>
document.querySelectorAll("#example/123");
</script>

Any idea why above id is not working? do I need extra library to escape the /?

Alicia Y
  • 247
  • 8
  • 2
    As you've discovered [slashes are not allowed](https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html). Try a hyphen instead, or move the 123 into a [data attribute](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes). Additionally there's no point in using `querySelectorAll` here as there should only be one element on the page that matches that selector (ids have to be unique). `querySelector` is enough. – Andy May 26 '22 at 11:43
  • To add to @Andy's point, you could just use the `getElementById` to be quite specific. – Anindya Dey May 26 '22 at 11:47
  • getElementById don't accept slash too – Alicia Y May 26 '22 at 11:50
  • Does this answer your question? [CSS selector to select an id with a slash in the id name?](https://stackoverflow.com/questions/5153986/css-selector-to-select-an-id-with-a-slash-in-the-id-name) – marekvospel May 26 '22 at 12:00

1 Answers1

1

You can escape the / using \\.

<h2 id="example/123">A heading</h2>

<script>
document.querySelectorAll("#example\\/123");
</script>

Duplicate of CSS selector to select an id with a slash in the id name?

However in this case you are using an id, so you can get the specific element without needing to get it from the NodeList using document.getElementById(), as only one element should have that id.

document.getElementById("hello/world");
marekvospel
  • 391
  • 1
  • 8