1

Need to check an ID whether is available in the DOM, before using the document.getElementById.

i.e. We have find() in jquery. Need to know the same in javascript

Please find the below example.

since dsp-store-name is not available in the DOM, its throwing the below exception in the console.

document.getElementById("dsp-store-name").innerHTML

VM655:1 Uncaught TypeError: Cannot read property 'innerHTML' of null at :1:43 (anonymous) @ VM655:1

Adam Azad
  • 11,171
  • 5
  • 29
  • 70
lokesh
  • 55
  • 4

4 Answers4

0

See if the result of the call is null before attempting to use the element:

var el = document.getElementById("dsp-store-name");
if (el != null)
   el.innerHTML = "hello";
Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

The only actual way is to select that element and verify if it exists.

var e = document.getElementById('dsp-store-name');
if(e){
   var eHTML = e.innerHTML;
   // rest of code. 
} else {
   // does not exist == 'null'
}
Adam Azad
  • 11,171
  • 5
  • 29
  • 70
0

check document.getElementById("dsp-store-name") for the null value, if element is not present document.getElementById() will return null.

console.log(document.getElementById("dsp-store-names"));
console.log(document.getElementById("dsp-store-name"));
<div id="dsp-store-name"></div>
Deep
  • 9,594
  • 2
  • 21
  • 33
-1

you can use this to check:-

if(document.getElementById("dsp-store-name") != null){
    var something=document.getElementById("dsp-store-name").innerHTML;
}
A Biswas
  • 421
  • 6
  • 12