简体   繁体   中英

How to check element exists?

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?

just check if you can select it:

$("#idname").length > 0

or

document.getElementById("idname") === null

You have to do the request inside your function! (See answer of Vohuman)

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

window.onbeforeunload = function(evt) {
   if ( document.getElementById("idname") ) {
      // ...
   }
}

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