How to check if an element exists in jQuery

In jQuery, you can use the .length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements.

For example,


if($('#div1').length){
	alert("Div1 exists");
}else{
	alert("Div1 does not exists");
}

To check if an element which has an id of “div1” exists.

jQuery length example


<html>
<head>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

</head>

<body>

<h1>jQuery check if an element exists</h1>

<script type="text/javascript">

  $(document).ready(function(){

    $("#buttonDiv1").click(function () {
		
	if($('#div1').length){
		alert("Div1 exists");
	}else{
		alert("Div1 does not exists");
	}
			
    });

    $("#buttonDiv2").click(function () {
		
	if($('#div2').length){
		alert("Div2 exists");
	}else{
		alert("Div2 does not exists");
	}
			
    });
	
  });
</script>
</head><body>

<div id="div1">
	<b>This is DIV element which has an ide of "div1"</b>
</div>

<br/>
<br/>
<br/>

<input type='button' value='div1 exists?' id='buttonDiv1'>
<input type='button' value='div2 exists?' id='buttonDiv2'>

</body>
</html>

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Manju
Guest
Manju

Very nice.
Thanks a lot

ali
Guest
ali

thanks..

Manan
Guest
Manan

Really helpful post for me :)

Thanks mkyong.

trackback
Vérifier l’existence d’un objet en JQuery | Balton

[…] Source Share this:TwitterFacebookJ'aime ceci:J'aimeSoyez le premier à aimer ceci. Cette entrée a été publiée dans Web et taguée JQuery, Objet. Ajouter aux Favoris le permalien. ← Infobulle en CSS […]

Ernesto Yat
Guest
Ernesto Yat

Thanks! It worked for me :)

Michael
Guest
Michael

You could try my plugin that I created.

Its called doesExist()

I had to check if an element exists over and over again so I decided to make a small plugin for that.

Usage:

$(‘mySelector’).doesExist() // returns true or false

Demo:
http://evilwebdesign.bplaced.net/doesExist

sadas
Guest
sadas

totally redundant!

Bangaru
Guest
Bangaru

Horrible English Mr. MK Yong, alert messages are to b like “div1 exists” and “div2 does not exist”.