Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if element with specific id exists or not

Tags:

javascript

dom

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

like image 449
Amita Patil Avatar asked Mar 01 '17 07:03

Amita Patil


People also ask

How do I find an element with a specific ID?

getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

How do you find if element with specific ID exists or not in jQuery?

In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.


3 Answers

 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

like image 196
Mr.Bruno Avatar answered Sep 29 '22 17:09

Mr.Bruno


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>
like image 28
Weedoze Avatar answered Sep 29 '22 17:09

Weedoze


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
}
like image 32
khoekman Avatar answered Sep 29 '22 16:09

khoekman