When you use document.getElementById on a non existing ID it returns 'null', not 'undefined'.


if(document.getElementById('testdiv') != null) {
// exists
} else {
// doesn't exist
}