To check if a div does not exist with JavaScript, we can check if the document.getElementById
or document.querySelector
returns a null
value.
For instance, we can write:
if (!document.getElementById("given-id")) {
console.log('not exist')
}
if (!document.querySelector("#given-id")) {
console.log('not exist')
}
We have 2 if statements.
The first one calls document.getElementById
to check if an element with the ID given-id
exists.
The 2nd one calls document.querySelector
to do the same thing.
They both log 'not exist'
since they don’t exist.
Also, we can write:
if (document.getElementById("given-id") === null) {
console.log('not exist')
}
if (document.querySelector("#given-id") === null) {
console.log('not exist')
}
to do the same thing by checking explicitly if null
is returned.
We should get the same result as before the elements with ID given-id
doesn’t exist.