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

Go To StackoverFlow.com

229

I’ve got a function that appends a <div> to an element on click. The function gets the text of the clicked element and assigns it to a variable called name. That variable is then used as the <div> id of the appended element.

I need to see if a <div> id with name already exists before I append the element but I don’t know how to find this.

Here is my code:

$("li.friend").live('click', function() {
  name = $(this).text();

  // if-statement checking for existence of <div> should go here
  // If <div> does not exist, then append element
    $("div#chatbar").append("<div class='labels'><div id='" + name + "' style='display:none;'></div>" + name + "</div>");

  // Else
    alert('this record already exists');
});

This seems pretty straightforward but I’m getting the error “Unexpected end of file while searching for class name”. I have no clue what that means.

if (document.getElementById(name)) {
  $("div#" + name).css({bottom: '30px'});
} else {
  $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
}

What’s more is that I want to be able to delete this element if I close it out which should then remove the div id [name] from the document but .remove() does not do this.

Here is the code for that:

$(".mini-close").live('click', function(){
  $(this).parent().remove();
});

I added .mini-close to the append function as a child of .labels so there was a way to close out of the appended <div> if needed. After clicking .mini-close and attempting to click the same name again from li.friends it still finds the div id [name] and returns the first part of my if statement.

2010-07-30 17:02
by sadmicrowave


490

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

if($("#" + name).length == 0) {
  //it doesn't 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 it's 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');
  }
});
2010-07-30 17:03
by Nick Craver
lots of jQuery in the non-jQuery part : - jAndy 2010-07-30 17:14
@Nick - this isnt working for me. While troubleshooting I alerted the length of the div id of [name] but it never finds it - sadmicrowave 2010-07-30 18:42
@sadmicrowave - Can you post some example markup? It's fairly straightforward so should work pretty easily - Nick Craver 2010-07-30 18:58
@Nick - please see my OP with new update - sadmicrowave 2010-07-30 19:18
checking == 0 isn't necessary if($("#" + name).length) { } works just fine - ScottE 2010-07-30 19:39
@ScottE - That's the inverse though, you mean !$("#"+name).length) : - Nick Craver 2010-07-30 20:12
@sadmicrowave - Is that your exact code? You're missing a "); on the end of that .append() line if so, see how your code format coloring is off - Nick Craver 2010-07-30 20:13
right, sorry nick, missed the - ScottE 2010-07-30 20:19
@Nick - sorry that wasnt my exact code I missed it when copying it to the window. Still having the specified problem... - sadmicrowave 2010-07-30 20:40
any additional ideas from anyone - sadmicrowave 2010-08-02 13:53
@sadmicrowave - Can you post your complete code? You don't show where you're creating the .mini-close elements, so I have no idea if your selectors/traversings are correct or not - Nick Craver 2010-08-02 14:00
I don't know what I was doing wrong but I got it to work now which means your suggestion was valid. Thanks Nick - sadmicrowave 2010-08-05 20:39
I don't quite understand how the second example is non-jQuery? Also, live is not only deprecated but deleted from v1.9 - rvighne 2014-03-01 19:48
@rvighne I was referring to the specific question piece, the existence check doesn't benefit from or need jQuery in many cases. The answer is from almost 4 years ago, can edit when not on a phone - Nick Craver 2014-03-01 20:15
I think you should do === instead of saw == - danger89 2019-02-26 22:10


60

Nick's 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
}
2010-07-30 19:36
by philo
you are right, this works great (I must have been doing something stupid). However when I replace the alert() with something else I get an error saying: "unexpected end of file while searching for class name". why is this happening? See my OP for what I'm replacing my alert() function with.. - sadmicrowave 2010-07-30 20:20
any additional ideas from anyone - sadmicrowave 2010-08-02 13:53
The error sounds like you're missing a bracket or a semi-colon - Rikki 2014-08-28 14:56
@Philo What if your looking to match specific ID's held in an array t - Beaniie 2016-10-04 12:23
You have several IDs in an array, and you want to find each of them? The brute force approach would be to loop over the array and call getElementById for each of them - philo 2016-10-04 17:08


26

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.

2013-10-08 13:46
by Tapan kumar


18

if($("#id").length) /*exists*/

if(!$("#id").length) /*doesn't exist*/
2014-04-04 01:29
by Kareem


7

if ( $( "#myDiv" ).length ) {
    //id id ( "#myDiv" ) is exist this will perform
    $( "#myDiv" ).show();

}

Another shorthand way:

    $( "#myDiv" ).length && $( "#myDiv" ).show();
2016-08-03 10:00
by Sanjib Debnath
why should "show" the div - ddb 2016-08-03 10:22
Its just a example inside the if function anything can write, when the id ( "#myDiv" ) is present that will perform - Sanjib Debnath 2016-08-03 10:30


5

You can check by using jquery simply like this:

if($('#divId').length!==0){
      Your Code Here
}
2013-11-04 04:25
by Hariprasath
if($('#divId').length!= 0){ Your Code Here } this would be correc - Santosh 2014-05-20 11:08


4

The most simple way is..

if(window["myId"]){
    // ..
}

This is also part of HTML5 specs: https://www.w3.org/TR/html5/single-page.html#accessing-other-browsing-contexts#named-access-on-the-window-object

window[name]
    Returns the indicated element or collection of elements.
2017-04-25 17:43
by rckd
This looks good but there's now a note https://www.w3.org/TR/html5/single-page.html#named-access-on-the-window-object that "relying on this will lead to brittle code" - Kivi Shapiro 2018-04-09 18:39


2

You can handle it in different ways,

Objective is to check if the div exist then execute the code. Simple.

Condition:

$('#myDiv').length

Note:

#myDiv -> < div id='myDiv' > <br>
.myDiv -> < div class='myDiv' > 

This will return a number every time it is executed so if there is no div it will give a Zero [0], and as we no 0 can be represented as false in binary so you can use it in if statement. And you can you use it as a comparison with a none number. while any there are three statement given below

// Statement 0
// jQuery/Ajax has replace [ document.getElementById with $ sign ] and etc
// if you don't want to use jQuery/ajax 

   if (document.getElementById(name)) { 
      $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 1
   if ($('#'+ name).length){ // if 0 then false ; if not 0 then true
       $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 2
    if(!$('#'+ name).length){ // ! Means Not. So if it 0 not then [0 not is 1]
           $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>"); 
    }
// Statement 3
    if ($('#'+ name).length > 0 ) {
      $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 4
    if ($('#'+ name).length !== 0 ) { // length not equal to 0 which mean exist.
       $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }
2017-03-02 07:06
by Ad Kahn


2

Here is the jQuery function I use:

function isExists(var elemId){
    return jQuery('#'+elemId).length > 0;
}

This will return a boolean value. If element exists, it returns true. If you want to select element by class name, just replace # with .

2017-08-11 11:25
by Sahan


1

put the id you want to check in jquery is method.

var idcheck = $("selector").is("#id"); 

if(idcheck){ // if the selector contains particular id

// your code if particular Id is there

}
else{
// your code if particular Id is NOT there
}
2014-04-28 07:30
by bhavya_w
Ads