[英]document.getElementById() only operated on one element
I wrote a simple const divFrame = document.getElementById("ethto-adfr")
and I use document.createElement("iframe")
and divFrame.appendChild(createFrame)
to create an iframe at the <div
s with the id
of ethto-adfr
.我写了一个简单的const divFrame = document.getElementById("ethto-adfr")
并使用document.createElement("iframe")
和divFrame.appendChild(createFrame)
在<div
的id
为ethto-adfr
It works great... but only on the first <div>
in the page.它工作得很好......但只在页面中的第一个<div>
上。 Is this just the way that document.getElementById
works?这就是document.getElementById
的工作方式吗? If so, how can I fix it?如果是这样,我该如何解决?
If you're referring to the fact that there can only be one unique id per html page, then that's how it's supposed to work.如果您指的是每个 html 页面只能有一个唯一 ID 的事实,那么它应该是这样工作的。 If you want to select multiple elements, you want to use class.如果要 select 多个元素,则要使用 class。
<div class="some_class_name"></div>
<div class="some_class_name"></div>
<div class="some_class_name"></div>
As mentioned by @vlaz, IDs should be unique.正如@vlaz 所提到的,ID 应该是唯一的。
That being said, document.querySelectorAll('#ethto-adfr')
might do the trick话虽如此, document.querySelectorAll('#ethto-adfr')
可能会成功
IDs are meant to be unique for an HTML page, you can instead use class for using in multiple places. ID 对于 HTML 页面来说是唯一的,您可以改用 class 在多个地方使用。
<div class="ethto-adrf"> ... </div>
<div class="ethto-adrf"> ... </div>
document.getElementsByClassName("ethto-adfr")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.