Web Development

Check Element Existence with MooTools and jQuery

Here I come up with the quick tip for Checking the existence of the element using the Two Major Javascript which are MooTools and jQuery.

This trick will be useful when you want to check if the element with specific ID is available in DOM or not. This tricks is preferable to use on domready event of the page. If you are not sure what does domready means then I suggest you to have a look at this article related to domready.

So without wasting the time have a look at codes in both the JavaScript Framework.

MooTools

Its prety simple to check the existence of element using MooTools. All you need is just an ID of the element. Have a look at below code block for the same:

[cc lang=”js”]
// ID is “my_element”

// METHOD 1
if($(‘my_element’))
{
// Element is exist
}

// METHOD 2
if(document.id(‘my_element’))
{
// Element is exist
}

[/cc]

jQuery

In jQuery, if you try the MooTools way then it will always show that element is exists. Try below code and see:

[cc lang=”js”]
// ID is “my_element”
// This is wrong way
if($(‘#my_element’))
{
// Element is Exists
}
[/cc]

The reason behind this is as follow:

Because in jQurey $(‘#ID’) will always return object, it will return blank object if element is not exists in DOM. So to really check the existence you need to use below code:

[cc lang=”js”]
// ID is “my_element”
// This is the corrent way in jQuery

if($(‘#my_element’).length>0)
{
// Element is exists
}
[/cc]

Share this article if you like this. Do not forgot to follow us and like us.

Shares:

Leave a Reply

Your email address will not be published. Required fields are marked *