document.getelementbyId will return null if element is not defined?

前端 未结 3 894

In my code, I see this:

if (document.getElementById(\'xx\') !=null) {
    //do stuff
}

if xx element is not defined, will this

3条回答
  •  心在旅途
    2020-12-29 19:15

    Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.

    Demo

    Html

    Javascript:

       if (document.getElementById('xx') !=null) 
         console.log('it exists!');
    
       if (document.getElementById('xxThisisNotAnElementOnThePage') ==null) 
         console.log('does not exist!');
    

提交回复
热议问题