Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

javascript - How to find if element with specific id exists or not

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.getElementById("myElement");
if(myEle  == null){
   var myEleValue= document.getElementById("myElement").value;
}

2).

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

but it gives same error as below -

Object expected

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
 var myEle = document.getElementById("myElement");
    if(myEle){
        var myEleValue= myEle.value;
    }

the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...