我想知道如何使用纯 javascript 获取元素。
我的代码如下:
<html>
<body>
<div id="abc" class="xy"> 123 </div>
<p id="abc" class="xyz"> 123 </p>
<span id="foo" class="foo2"> foo3 </span>
</body>
</html>
在这里我想找到具有组合的元素:
- 找到 id 为 abc 和标记名为 p 的元素
- 找到 id 为 abc 和类名为 xy 的元素
- 找到具有类名 foo2 和标记名 span 的元素
- 找到具有 id abc 和类名 xy 以及标记名 div 的元素
我知道每个页面不能使用多个 id。但在更糟糕的情况下,不同的标签可以使用相同的 ID 吗?在 html 中?
最佳答案
您可以使用 querySelectorAll
获得更多“高级”选择。对于你的三个例子:
document.querySelectorAll("p#abc")
document.querySelectorAll(".xy#abc")
document.querySelectorAll("span.foo2")
关于javascript - getelementbyid 和标记名和类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12011867/