Check if a div does NOT exist with javascript

前端 未结 9 2163
野性不改
野性不改 2020-12-12 16:42

Checking if a div exists is fairly simple

if(document.getif(document.getElementById(\'if\')){

}

But how can I check if a div with the give

相关标签:
9条回答
  • 2020-12-12 17:21

    getElementById returns null if there is no such element.

    0 讨论(0)
  • 2020-12-12 17:24

    I do below and check if id exist and execute function if exist.

    var divIDVar = $('#divID').length;
    if (divIDVar === 0){ 
        console.log('No DIV Exist'); 
    } else{  
        FNCsomefunction(); 
    }   
    
    0 讨论(0)
  • 2020-12-12 17:28

    Try getting the element with the ID and check if the return value is null:

    document.getElementById('some_nonexistent_id') === null
    

    If you're using jQuery, you can do:

    $('#some_nonexistent_id').length === 0
    
    0 讨论(0)
  • 2020-12-12 17:31

    There's an even better solution. You don't even need to check if the element returns null. You can simply do this:

    if (document.getElementById('elementId')) {
      console.log('exists')
    }
    

    That code will only log exists to console if the element actually exists in the DOM.

    0 讨论(0)
  • 2020-12-12 17:33

    All these answers do NOT take into account that you asked specifically about a DIV element.

    document.querySelector("div#the-div-id")
    

    @see https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

    0 讨论(0)
  • 2020-12-12 17:35
    if (!document.getElementById("given-id")) {
    //It does not exist
    }
    

    The statement document.getElementById("given-id") returns null if an element with given-id doesn't exist, and null is falsy meaning that it translates to false when evaluated in an if-statement. (other falsy values)

    0 讨论(0)
提交回复
热议问题