[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

This question is related to javascript dom

The answer is


document.getElementById('yourId')

is the correct way.

the document refers the HTML document that is loaded in the DOM.

and it searches the id using the function getElementById() which takes a parameter of the id of an element

Solution will be :

var elem = (document.getElementById('myElement'))? document.getElementById('myElement').value : '';

/* this will assign a value or give you and empty string */

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
}

Use typeof for elements checks.

if(typeof(element) === 'undefined')
{
// then field does not exist
}

You can simply use if(yourElement)

_x000D_
_x000D_
var a = document.getElementById("elemA");_x000D_
var b = document.getElementById("elemB");_x000D_
_x000D_
if(a)_x000D_
  console.log("elemA exists");_x000D_
else_x000D_
  console.log("elemA does not exist");_x000D_
  _x000D_
if(b)_x000D_
  console.log("elemB exists");_x000D_
else_x000D_
  console.log("elemB does not exist");
_x000D_
<div id="elemA"></div>
_x000D_
_x000D_
_x000D_


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; 
}