0

How do i go about this?

i tried doing if(document.getElementById("cart-remove")[0]) but that gives me the error: ERROR: Execution of script 'New Userscript' failed! Cannot read property '0' of null

Thanks Alot.

Gunnar Marino
  • 83
  • 3
  • 8
  • It should be `document.getElementById("cart-remove")` – Mamun Nov 12 '17 at 05:12
  • 1
    what people are trying to say is that `document.getElementById` returns a single element, never an array (or array-like object) - despite the number of non-unique ID's in your HTML ... you're confused with `getElementsByClassName` or `getElementsByTagName` which return a "collection" - but as you can see, the function names are `getElements` ... plural, whereas getElementById Element is singular – Jaromanda X Nov 12 '17 at 05:15

5 Answers5

1

Use this code:

if(document.getElementById("cart-remove"))
{
    // some code here
}
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Dmitriy Buteiko
  • 624
  • 1
  • 6
  • 14
0

you can try if (document.getElementById("cart-remove") === null) { ..... }

daniel.gindi
  • 3,457
  • 1
  • 30
  • 36
guyz92
  • 15
  • 4
0
if(document.getElementById("cart-remove")){}

if document.getElementById("cart-remove") is null, then document.getElementById("cart-remove")[0] will give you an error.

You can also do:

if(document.getElementById("cart-remove") && document.getElementById("cart-remove")[0]){}

Since document.getElementById("cart-remove")[0] will give you an error if document.getElementById("cart-remove") is null, you first check document.getElementById("cart-remove") and then document.getElementById("cart-remove")[0].

li_
  • 124
  • 1
  • 9
0

null is one of the falsy values in Javascript

if(document.getElementById("car-remove"))
Shuyou
  • 81
  • 1
  • 5
0

Use equality === check inside if condition

if (document.getElementById('x') === null) {
  console.log('It is null')
}
<div id="test">Test</div>
brk
  • 48,835
  • 10
  • 56
  • 78