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
  • 367
  • 5
  • 12
  • 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

2 Answers2

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
  • 412
  • 4
  • 9
-1

Well, sometimes when newbies are learning JS so they make the mistake of linking the Javascript Link between two HTML Tags. Always use the Js linking scripts between the body tags.

Popular Solution :

Link your JS between HTML Tags :)

let para = document.querySelectorAll('h1');
para.forEach((allpara) => {
  console.log(allpara)
});
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>JavaScript Learning Project</title>
 </head>
  <body>
  
  <h1> This is 1st </h1>
  <h1> This is 2nd </h1>
  <h1> This is 3rd </h1>
  <h1> This is 4th </h1>
  
  
  
 <script src="index.js"></script>
  </body>
</html>
Khalid
  • 9
  • 3
  • I'm really not sure what you are trying to say here, but it doesn't appear to be related to the problem described in the question (which was solved, and has an accepted answer, in May last year). – Quentin Jan 24 '23 at 10:42