简体   繁体   中英

emit events to all child nodes of a html dom element

I need to emit an event to all deep childNodes of an element. What i am looking is event capturing using custom events or something equivalent.

one of the solution is to recursive loop through all children and then emit events to each one, but it is slower.

is there any better solution ?

Not sure what you mean with deep childNodes, but querySelectorAll can select all elements at any nesting level starting from a root node:

 const elems = root.querySelectorAll("*") const customEvent = new CustomEvent('custom') elems.forEach(el => { el.addEventListener("custom", (e) => console.log("Custom event received on element:", e.currentTarget)) el.dispatchEvent(customEvent) })
 <div id="root"> <button>B1</button> <p>P1</p> <div> <p>P2</p> <p>P3</p> <button>B2</button> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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