How to find if element with specific id exists or not

前端 未结 6 1927
独厮守ぢ
独厮守ぢ 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条回答
  •  猫巷女王i
    2020-12-08 04:47

    You can simply use if(yourElement)

    var a = document.getElementById("elemA");
    var b = document.getElementById("elemB");
    
    if(a)
      console.log("elemA exists");
    else
      console.log("elemA does not exist");
      
    if(b)
      console.log("elemB exists");
    else
      console.log("elemB does not exist");

提交回复
热议问题