Ad

How To Check Element Exists?

- 1 answer

I need to check if element (#idname) exists, then alert a message to user before closing current tab (or browser).

Here is my condition:

if (document.contains(document.getElementById("#idname"))) {
    window.onbeforeunload = function(evt) {
      // some code here
}

The above code works as well, but my problem is that element (#idname) isn't exist in the HTML in first and I will append it to my HTML after page loading. Now that condition doesn't work anymore. Is there any solution?

Ad

Answer

You can simply check the existence of the element in your onbeforeunload handler:

window.onbeforeunload = function(evt) {
   if ( document.getElementById("idname") ) {
      // ...
   }
}
Ad
source: stackoverflow.com
Ad