javascript – How to find if div with specific id exists in jQuery?

javascript – How to find if div with specific id exists in jQuery?

You can use .length after the selector to see if it matched any elements, like this:

if($(# + name).length == 0) {
  //it doesnt exist
}

The full version:

$(li.friend).live(click, function(){
  name = $(this).text();
  if($(# + name).length == 0) {
    $(div#chatbar).append(<div class=labels><div id= + name +  style=display:none;></div> + name + </div>);
  } else {
    alert(this record already exists);
  }
});

Or, the non-jQuery version for this part (since its an ID):

$(li.friend).live(click, function(){
  name = $(this).text();
  if(document.getElementById(name) == null) {
    $(div#chatbar).append(<div class=labels><div id= + name +  style=display:none;></div> + name + </div>);
  } else {
    alert(this record already exists);
  }
});

Nicks answer nails it. You could also use the return value of getElementById directly as your condition, rather than comparing it to null (either way works, but I personally find this style a little more readable):

if (document.getElementById(name)) {
  alert(this record already exists);
} else {
  // do stuff
}

javascript – How to find if div with specific id exists in jQuery?

Try to check the length of the selector, if it returns you something then the element must exists else not.

if( $(#selector).length )         // use this if you are using id to check
{
     // it exists
}


if( $(.selector).length )         // use this if you are using class to check
{
     // it exists
}

Use the first if condition for id and the 2nd one for class.

Leave a Reply

Your email address will not be published.