3

When searching for one or more dom elements using document.getElementById, a single dom element is returned with typeof(node) -> "object".

If no dom element is found for the query, a null object is returned which also gives typeof(node) -> "object".

caseOne = document.getElementById('contentSub')
   -> <div id="contentSub">
typeof(caseOne)
   -> "object"

caseTwo= document.getElementById('qwert')
   -> null
typeof(caseTwo)
   -> "object"

How to check whether a call to document.getElementById has been successful, in the sense that a dom element has been returned that may be further processed?

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
3840
  • 376
  • 3
  • 16

3 Answers3

3

Well to check if the returned object isn't undefined, simply use !caseOne:

var caseOne = document.getElementById('contentSub')
if(!caseOne){
    //It's undefined
}
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
1

You can achieve that by simple evaluation condition for the returned element object of method document.getElementById:

if(document.getElementById('contentSub') != null){
     console.log("element exists");
}
else {
     console.log("element doesn't exist");
}
Oghli
  • 2,200
  • 1
  • 15
  • 37
0

To check whether a the returned value has something in it, you can create your own method like isEmpty().

function isEmpty(value){
    return value === null || typeof(value) === 'undefined' || value === ''
}

This method checks all cases.

SBylemans
  • 1,764
  • 13
  • 28