Jump to content

If Element Exists (cross Browser)


johnnyg24

Recommended Posts

I am looking for a sure fire way to see if an element exists on a page. I have searched this topic and there seems to be a lot of ways to do it but I want to know what is the best and most accurate way of detecting an element. I use the following but Im not sure if it's best practice:

if(document.getElementById("elem")){alert("exists")}else{alert("does not exist")}

Link to comment
Share on other sites

I use typeof:
if((typeof document.getElementById("elem")) != 'undefined'){  alert("exists")}else{  alert("does not exist")}

Is there any benefits of using typeof over OP's method? I have always done it like the first example.
Link to comment
Share on other sites

If you're testing an object it doesn't matter much, I use typeof in several situations though so I use it here also. If you want to check if an object has a property defined you should use typeof, just doing a boolean check will come back false if the property is defined but has a false value. I also use it to test whether a variable is a function.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...