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


 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


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");
<div id="elemA"></div>