How to find if element with specific id exists or not

前端 未结 6 1920
独厮守ぢ
独厮守ぢ 2020-12-08 04:18

In my JavaScript I want to check whether the element with specific id is exist or not, I tried it with 2 ways

1).

var myEle = document.getElementByI         


        
6条回答
  •  情歌与酒
    2020-12-08 05:02

    getElementById

    Return Value: An Element Object, representing an element with the specified ID. Returns null if no elements with the specified ID exists see: https://www.w3schools.com/jsref/met_document_getelementbyid.asp

    Truthy vs Falsy

    In JavaScript, a truthy value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN). see: https://developer.mozilla.org/en-US/docs/Glossary/Truthy

    When the dom element is not found in the document it will return null. null is a Falsy and can be used as boolean expression in the if statement.

    var myElement = document.getElementById("myElement");
    if(myElement){
      // Element exists
    }
    

提交回复
热议问题