Jump to content

If Element Exists (cross Browser)


johnnyg24
 Share

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")}

Edited by johnnyg24
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...