首页 > 解决方案 > 如何获取在 getElementsByTagName 中返回的 DOM 子数组中的元素

问题描述

有没有办法检测从 getElementsByTagName() 返回的代理对象中的元素?我需要从下面的代码将EventListener 添加到返回的svgs

const svgs= document.getElementsByTagName('svg');
console.log('svgs',svgs);
const myArray = Array.from(svgs); 
console.log('myArray ',myArray); // This is returning [] 

下面是我可以在控制台中看到的日志。有人可以帮我将 svgs=>target=>HTMLCollection(49) 放入数组吗 在此处输入图像描述

标签: javascripthtmlarrays

解决方案


原因是这些svg元素显然是异步添加到文档中的。当您查看控制台并打开svgs结构时,svg元素已被加载,但在您的代码运行并创建数组时情况并非如此。您看到它们是因为控制台的延迟加载

如果svg元素是在页面加载时加载的,那么您可能很幸运,您可以将代码包装成如下内容:

window.onload = () => { /* your code */ }

但更有可能的是,这些内容是通过一些 Ajax 调用加载的,然后上面的方法就无济于事了。

你可以监听 DOM 突变事件:

const svgs = document.getElementsByTagName('svg');
console.log(svgs.length); // <-- presumably outputs 0

const listener = new MutationObserver(updated);
// This listens to changes under the BODY element. If you can be more 
// precise, then do so (to save resources). If you can do without
// the subtree option, then that is also preferred:
listener.observe(document.body, { childList: true, subtree: true });

function updated() {
    console.log(svgs.length); // <-- notice the increased length
    // Do whatever else you want to do with this collection.

    // If you are sure you have all you need, then stop the listener:
    listener.disconnect();
}

如果元素“一次”全部填充,并且您只需要一次调用事件侦听器,那么您可能仍需要使用一些去抖动模式对其进行调整。


推荐阅读