Marco Marco - 1 year ago 65
jQuery Question

verify if element exists, if not create the element once

Using jQuery, i'm trying to figure out if a div exists before I create one using the function create_modal().

Doing some research here, I came up with this simple code:


var name = "modalAuthorWork";

var modalwnd = $(name);

# create the modal once
if ( !modalwnd.length ) {

Here's the problem, the function create_modal() executes all the time. I know for a fact that the function does indeed create the new div, so that part works ok. So, i guess it does not check correctly if the div exists in the first place...

How do i fix this simple code?

Answer Source

You're not checking for a div. You're checking for a literal DOM element whose tag name is <modalAuthorWork>.

if you want to check for an ID or css class of that name, it should be

 $('div#modalAuthorWork') // div  with ID modalAuthorWork
 $('div.modalAuthorWork') // div with css class modalAuthorWork


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download