简体   繁体   English

JavaScript我如何遍历HTMLcollection中的每个当前和将来的元素?

[英]JavaScript how do i iterate over every current and future element in a HTMLcollection?

An HTMLCollection in the HTML DOM is live; HTML DOM中的HTMLCollection是实时的; it is automatically updated when the underlying document is changed. 当基础文档更改时,它会自动更新。

im trying to write a simple script, for a website that often adds elements, that recolors those elements based on criteria. 我试图为一个经常添加元素的网站编写一个简单的脚本,该脚本根据条件为这些元素重新着色。

now, i dont want to have a loop continusly running and checking for new elements, for performance reasons. 现在,出于性能原因,我不想让循环持续运行并检查新元素。

how would i use a live HTMLcollectio nand execute a function on every element in it, even the new ones added? 我将如何使用实时HTML集合并在其中的每个元素上执行一个函数,甚至添加了新元素?

if i can accomplish this, it should result in a script that never finishes, and recolors all new elements. 如果我能做到这一点,它将导致脚本永远无法完成,并为所有新元素重新着色。

any help appreciated! 任何帮助表示赞赏!

I would use a MutationObserver to accomplish this task. 我将使用MutationObserver完成此任务。 It will watch a node for changes, and if needed it will watch the subtree for changes as well (which I don't think is needed here). 它将监视节点的更改,并且如果需要,还将监视子树的更改(我认为这里不需要)。 As nodes get added, we can send the node to a function to apply some feature on it. 添加节点后,我们可以将节点发送给函数以在其上应用某些功能。 In the example below we just randomly select a color and set the background. 在下面的示例中,我们只是随机选择一种颜色并设置背景。

 let targetNode = document.getElementById('watch') // Apply feature on the node function colorNode(node) { let r = Math.floor(Math.random() * 255) let g = Math.floor(Math.random() * 255) let b = Math.floor(Math.random() * 255) node.style.background = `rgb(${r},${g},${b})` } // Watch the node for changes (you can watch the subTree if needed) let observerOptions = { childList: true } // Create the callback for when the mutation gets triggered let observer = new MutationObserver(mutationList => { // Loop over the mutations mutationList.forEach(mutation => { // For added nodes apply the color function mutation.addedNodes.forEach(node => { colorNode(node) }) }) }) // Start watching the target with the configuration observer.observe(targetNode, observerOptions) ///////////////// /// Testing ///////////////// // Apply the inital color Array.from(targetNode.children).forEach(child => colorNode(child)) // Create nodes on an interval for testing setInterval(() => { let newNode = document.createElement('div') // Some random text newNode.textContent = (Math.random() * 1000).toString(32) targetNode.appendChild(newNode) }, 2000) 
 <div id="watch"> <div>One</div> <div>Two</div> <div>Three</div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM