简体   繁体   English

select id 包含带有 querySelectorAll 的斜线不起作用

[英]select id contain slash with querySelectorAll is not working

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

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

Any idea why above id is not working?知道为什么上面的 id 不起作用吗? do I need extra library to escape the / ?我需要额外的库来转义/吗?

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?重复CSS 选择器以选择 ID 名称中带有斜杠的 ID?

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.但是,在这种情况下,您使用的是 id,因此您可以获取特定元素,而无需使用 document.getElementById() 从 NodeList 中获取它,因为只有一个元素应该具有该 id。

document.getElementById("hello/world");

Well, sometimes when newbies are learning JS so they make the mistake of linking the Javascript Link between two HTML Tags.好吧,有时新手在学习 JS 时,他们会错误地将两个 HTML 标签之间的 Javascript 链接链接起来。 so they code you for selecting a particular HTML element in Js and will not pick up the HTML Tags.所以他们编码你在 Js 中选择一个特定的 HTML 元素并且不会选择 HTML 标签。

Popular Solution:流行的解决方案:

Link your JS between HTML Tags:)在 HTML 标签之间链接你的 JS :)

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM