93

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

isherwood
  • 58,414
  • 16
  • 114
  • 157
Amita Patil
  • 1,310
  • 2
  • 14
  • 22
  • 4
    It's `document.getElementById()` – Andreas Mar 01 '17 at 07:53
  • 2
    In your 1st case you're saying if the element is null then get it's value, you should be checking that if it's not null (or rather if it's truthy as you're doing in case 2). The other thing is you need to use `document.getElementById()` – winhowes Mar 01 '17 at 07:55
  • yea I did same in my code, here its by mistake – Amita Patil Mar 01 '17 at 07:56
  • just change to `myEle != null`, `document.getElementById()` returns null if an element with the required id was not found (see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) – TastySpaceApple Mar 01 '17 at 07:58
  • 2
    @AmitaPatil you must not edit the question to an answer! You must keep the code that originated the problem! – ibrahim mahrir Mar 01 '17 at 08:01

8 Answers8

188
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

STA
  • 30,729
  • 8
  • 45
  • 59
LellisMoon
  • 4,810
  • 2
  • 12
  • 24
  • 1
    You mean document.getElementById("myElement") this returns boolean value ? – Amita Patil Mar 01 '17 at 07:55
  • 5
    use `if(myEle!=null){}` – Deep 3015 Mar 01 '17 at 07:56
  • 3
    @AmitaPatil no it doesn't, but you can check if a variable is defined only checking it in an if, if the variable myEle isn't defined the if will choose the else block of code – LellisMoon Mar 01 '17 at 07:56
  • 2
    You should also consider wrapping that inside the load event callback as if the DOM is not loaded the if will never be executed even if the element will be there! – ibrahim mahrir Mar 01 '17 at 07:58
  • 1
    @ibrahimmahrir I just modified his piece of code, if the problem is on load please edit the question with other code to show us what is your problem – LellisMoon Mar 01 '17 at 07:59
  • Ok so yeah. Where exactly do I put this code? It is not like it will execute automatically when the elements are added I mean it's not Jetpack Compose. What do you say to that? Thanks, – Richard Onslow Roper Nov 12 '21 at 15:43
  • Well, it depends on the moment in which you need to verify the element exist, on window load or inside a function that need to check that. – LellisMoon Nov 15 '21 at 13:18
  • How come it wasn't required of you to use .length for myEle? – klewis Feb 10 '23 at 14:43
  • @klewis getElementById returns a single HTMLElement or null, so you can't verify a length, maybe you are confused with querySelectorAll? – LellisMoon Mar 22 '23 at 13:28
15

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>
Weedoze
  • 13,683
  • 1
  • 33
  • 63
11

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
}
khoekman
  • 1,153
  • 7
  • 16
4
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 */
Star
  • 3,222
  • 5
  • 32
  • 48
Rahil Lakhani
  • 412
  • 4
  • 7
4

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; 
}
Armin
  • 220
  • 2
  • 10
3

Use typeof for elements checks.

if(typeof(element) === 'undefined')
{
// then field does not exist
}
Debbie Kurth
  • 403
  • 3
  • 16
3
if( document.getElementById("myElement") ){
   console.log('exists');
}

or shorter way

if( document.querySelector("#myElement") ){}
Farzad.Kamali
  • 553
  • 4
  • 10
2

this works for me to check if element exits

let element = document.getElementById("element_id");
if (typeof(element) !== 'undefined' && element!== null)
{
    //content
}
iohan sandoval
  • 179
  • 1
  • 6