johnnyg24 Posted November 20, 2009 Share Posted November 20, 2009 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 More sharing options...
jeffman Posted November 20, 2009 Share Posted November 20, 2009 Assuming the element has an id (which is good practice) that's the way. Link to comment Share on other sites More sharing options...
justsomeguy Posted November 20, 2009 Share Posted November 20, 2009 I use typeof: if((typeof document.getElementById("elem")) != 'undefined'){ alert("exists")}else{ alert("does not exist")} Link to comment Share on other sites More sharing options...
Err Posted November 25, 2009 Share Posted November 25, 2009 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 More sharing options...
justsomeguy Posted November 25, 2009 Share Posted November 25, 2009 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 More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.