替换属于特定类的所有元素 [英] replace all elements belonging to a specific class
问题描述
我正在尝试开发嵌入式小部件。用户将在其页面中包含锚
标记和javascript,并且它将呈现内容。与嵌入式推文类似。
I was trying to develop an embedded widget. User would include an anchor
tag and a javascript in their page, and it would render the content. Similar to embedded tweets.
<a href="http://localhost:3000/user/13"
target="_blank"
class="my-widget"
data-widget-type="profile"
data-widget-identifier="id"
data-identifier-value="13"
>Sayantan Das</a>
</div>
<script src="//localhost/my-widget/js/widget.js" async ></script>
从 widget.js
,我会使用 class =my-widget
获取所有元素,并替换为 iframe
。
And from widget.js
, i would get all the elements with class="my-widget"
and replace with an iframe
.
widgets.js
!function(global, document) {
global.MyWidgets = global.MyWidgets || {};
for(let widgets = document.getElementsByClassName('my-widget'), i = 0; i < widgets.length; i++) {
console.log(widgets)
let element = widgets[i];
let span = document.createElement('span');
span.innerHTML = "Changed from widget " + i;
element.parentNode.appendChild(span);
element.parentNode.removeChild(element);
}
}(window, document);
问题是,当我删除元素时,循环也会运行一个较短的数字。例如,如果有两个元素具有类 my-widget
,则在第一次循环运行并删除一个元素并且循环仅运行一次之后。如何替换所有元素?
The problem is , when I remove the element the loop also runs for a shorter number. for example, if there are two elements with class my-widget
, after first time the loop runs and one element is removed and the loop runs only once. How do I replace all the elements?
推荐答案
那是因为 getElementsByClassName
返回直播 HTMLCollection
;当您从DOM中删除 class =my-widget
元素时,它也会从集合中删除。
That's because getElementsByClassName
returns a live HTMLCollection
; when you remove the class="my-widget"
element from the DOM, it's also removed from the collection.
要么在集合中向后工作(所以你要从最后删除,这不会影响它之前的那些),或者使用 querySelectorAll(。my-widget)
相反,它返回一个快照 NodeList
,而不是实时 HTMLCollection
。
Either work backward through the collection (so you're removing from the end, which doesn't affect the ones before it), or use querySelectorAll(".my-widget")
instead, which returns a snapshot NodeList
, not a live HTMLCollection
.
向后工作:
for(let widgets = document.getElementsByClassName('my-widget'), i = widgets.length - 1; i >= 0; i--) {
使用qSA代替:
for(let widgets = document.querySelectorAll('.my-widget'), i = 0; i < widgets.length; i++) {
或者如果你不需要 i
(您似乎只是用它来获取元素并用于演示目的),您可以使用 for-of
with NodeList
现在(在大多数平台上; 此答案为其他人提供了polyfill):
or if you don't need i
(you seem only to be using it to get the element and for demo purposes), you can use for-of
with NodeList
s now (on most platforms; this answer has a polyfill for others):
for (const element of document.querySelectorAll('.my-widget')) {
// ...and remove the `let element = ...` line
这篇关于替换属于特定类的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!