How to find if element with specific id exists or not

前端 未结 6 1934
独厮守ぢ
独厮守ぢ 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 04:44

    You need to specify which object you're calling getElementById from. In this case you can use document. You also can't just call .value on any element directly. For example if the element is textbox .value will return the value, but if it's a div it will not have a value.

    You also have a wrong condition, you're checking

    if (myEle == null)

    which you should change to

    if (myEle != null)

    var myEle = document.getElementById("myElement");
    if(myEle != null) { 
        var myEleValue= myEle.value; 
    }
    

提交回复
热议问题