Check Element Existence with MooTools and jQuery

  • Avinash
  • 0
  • Jun 19, 2012
  • Tips & Tricks

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:

// ID is "my_element" // METHOD 1 if($('my_element')) { // Element is exist } // METHOD 2 if(document.id('my_element')) { // Element is exist }
  // ID is "my_element"
 
  // METHOD 1
  if($('my_element'))
  {
    // Element is exist
  }
 
  // METHOD 2
  if(document.id('my_element'))
  {
    // Element is exist
  }

jQuery

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

// ID is "my_element" // This is wrong way if($('#my_element')) { // Element is Exists }
  // ID is "my_element"
  // This is wrong way
  if($('#my_element'))
  {
    // Element is Exists
  }

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:

// ID is "my_element" // This is the corrent way in jQuery if($('#my_element').length>0) { // Element is exists }
  // ID is "my_element"
  // This is the corrent way in jQuery
 
  if($('#my_element').length>0)
  {
    // Element is exists
  }

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

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: