Hello,
So a friend of mine asked me a question that if there is a function in jQuery that makes it simple to check if a element with an ID exist in DOM or not. So I think that function does not exist but its pretty simple to write one.
Ok first things first, here is a simple way to check if an element exist or not.
Markup
Here is an example markup on which our jQuery code will be based on
1 |
<did id="myDiv"></div> |
A simple check (This is how you do it anyway)
1 2 3 4 5 6 |
if(jQuery("#myDiv").length) { // element exist } else { // tooth fairy took it } |
So above works pretty well and it will work pretty well with the CSS class selectors too.
But just if you are after exists() function here is what you can do 🙂 The only advantage is readability of your code.
Now lets write a little plugin so that you can hook it in your code easily
1 2 3 4 5 6 7 8 9 10 |
jQuery.fn.exists = function(){ return this.length; } if (jQuery("#myDiv").exists()) { // Yay! It exists } else { // tooth fairy took it again :( } |
So to be generic in nature here is a generic definition for our exists() function for jQuery
1 |
/* returns a number */ |
1 |
jQuery(selector).exists(); |
To make our function return boolean true or false we just need to change the condition in our plugin function as shown below
1 2 3 4 |
jQuery.fn.exists = function(){ // return true if element exists return this.length > 0; } |
I hope that this helps.
If you would like to add something or make a correction please leave your comments
Cheers
Leave a Reply