Posts Tagged ‘DOM’

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
      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 !!!