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
  • 30,215
  • 7
  • 54
  • 72
3840
  • 366
  • 2
  • 15

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
  • 30,215
  • 7
  • 54
  • 72
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
  • 1,733
  • 1
  • 11
  • 33
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,716
  • 13
  • 27