2

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?

Shafizadeh
  • 9,960
  • 12
  • 52
  • 89

2 Answers2

2

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)

Jarlik Stepsto
  • 1,667
  • 13
  • 18
2

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

window.onbeforeunload = function(evt) {
   if ( document.getElementById("idname") ) {
      // ...
   }
}
Ram
  • 143,282
  • 16
  • 168
  • 197
  • Can I ask another question? *(it isn't related to the above question, it is a small question which doesn't has enough worth to I ask it on SO)* – Shafizadeh Jan 19 '16 at 01:25
  • Thanks *(my Iranian friend)* ..! Well I'm trying to create a small markdown editor *(something like SO's textarea)*, [Here is a small demo](http://jsfiddle.net/3g3gf7kq/8/) of that. There is just one button *(named Bold)* which appends two stars `**` around selected/highlighted text. – Shafizadeh Jan 19 '16 at 01:35
  • Now, what's the problem? That is: **bad-handling-spaces-around-highlighted-text** ..! To solve that problem, I have created a regex to handle spaces as well like this: `$textarea.val( $textarea.val().replace(/\s*(\*+)\s*(.*?)\s*(\*+)\s*/g,' $1$2$3 ') );` – Shafizadeh Jan 19 '16 at 01:35
  • The above regex should be paste on line 13 of that fiddle and it works as well. But it has a new problme, When I use that regex, the text-highlighting hides after clicking on Bold, Well do you know any workaround to I have both text-highlighting and using that regex? – Shafizadeh Jan 19 '16 at 01:36
  • The google CDN has been filtered in Iran and the demo isn't run properly for me. Well, let me answer your question tomorrow, It's 5 a.m. and I'm sleepy right now. – Ram Jan 19 '16 at 01:47