Nifty Javascript Hack : how to check if an element exists in the document

Here is a nifty javascript hack for how to check whether an element exists in the document or not. Lets say that the name of the element in the question is “status”. Getting the element by getElementsByName and checking the results against null wont help at all. getElementById wont help either because the document apis actually return an empty object and not a null value.
// The following Code will fail
var check = document.getElementsByName("status");                  //here status
if(check)
{
      alert('Did not expect it');
}
The alert will popup even if the element named ‘status’ does not exist in the document. To work around the problem you will need to find the size of the output from getElementsByName and check it against zero as illustrated below:
// This code works as expected
if(check.length != 0)
{
      alert('Got Expected Alert');
}
The alert in this case will pop out only if the element named status exists in the document. Hope the trick helps some one. Let me know in comments in case of any doubts !!!
  • http://twitter.com/scriblogs Scriblogs

    i will like to see this handled via getElementById and its behavior

  • http://twitter.com/scriblogs Scriblogs

    i will like to see this handled via getElementById and its behavior

  • Manish Goyal

    I don’t understand what is the use of this trick actually?

    • Anonymous

      JS is a script which stops executing at first error/warning. Sometimes, before performing any operation such as getting the value you need to check if that element exists. In such cases the above mentioned code helps saving you from obvious pitfall of using if(check)…

  • Veler

    Oooh finaly found something usefull. Been chewing my ears off trying to find a way to do it with getElementById.

    Cheers for the nice trick mate !