I want to check whether element attached to the DOM in javascript because I want to do some action when element gets attached to the DOM(on element attach event I want to do some action). Is there anything like addAttachHandler like GWT which is also present in javascript?
-
Your title might be better as "Detect when element attached to DOM". ;-)RobG– RobG2018-09-21 11:29:13 +00:00Commented Sep 21, 2018 at 11:29
-
Maybe developer.mozilla.org/en-US/docs/Web/API/MutationObserver/… ..?Teemu– Teemu2018-09-21 11:33:28 +00:00Commented Sep 21, 2018 at 11:33
Add a comment
|
1 Answer
You can use MutationObserver which tells you when elements are added or removed from the DOM tree. It is fully supported by all modern browsers (IE11+).
The Elemento library (Apache 2.0 license) has a GWT JsInterop implementation of an attach/detach listener that uses MutationObserver behind the scenes. You might be able to draw inspiration from that code, or use it directly.
2 Comments
Kyle Baker
Please add a code example rather than referring to links.
ᴇʟᴇvᴀтᴇ
@Kyle Baker, I would normally show code, but the question doesn't actually ask for a code sample, and it'd take some time to put together a good example, so I tried to hint at the direction and leave it as "an exercise for the reader". It would be great if you can add an answer with code examples though.