jQuery Element exists function

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

 A simple check (This is how you do it anyway)

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

 

 

So to be generic in nature here is a generic definition for our exists() function for jQuery

To make our function return boolean true or false we just need to change the condition in our plugin function as shown below

I hope that this helps.

If you would like to add something or make a correction please leave your comments

Cheers

 

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.