javascript - 如何获取在 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) 放入数组吗
解决方案
原因是这些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();
}
如果元素“一次”全部填充,并且您只需要一次调用事件侦听器,那么您可能仍需要使用一些去抖动模式对其进行调整。
推荐阅读
- java - 在 Oracle 数据库中上传 jar 时获取不同的 AES 加密值
- google-speech-to-text-api - error.runtime.java.lang.NoClassDefFoundError ,错误处理请求,java.lang.NoClassDefFoundError: com/google/cloud/speech/v1/SpeechClient
- javascript - azure函数将pdf转换为node.js中的图像?
- alsa - Liquidsoap 无法识别 alsa
- android - 如何在 Android 中使用无栏和全屏主题?
- html - 顶部 CSS 属性无法正常工作,而左侧工作正常
- javascript - 需要 ejs 文件中 app.js 中 html 标记的 ID
- python - 使用 sqlalchemy 将数据加载到 Oracle 数据库时,不允许使用“Multi”方法
- python - 按分组数据框上的前 n 个结果可视化列
- websocket - aiohttp websocket