Just for fun, you can also use a live collection for this (they are provided as part of the DOM). You can set up a collection of all divs on the page (this can be done in the head before loading the body):
var allDivs = document.getElementsByTagName('div');
Any div with id is available as a named property of the collection, so you can do:
if (allDivs.someId) {
If the identifier is not a valid identifier or is held in a variable, use a square bracket notation. Some replay codes:
<button onclick=" alert(!!allDivs.newDiv); ">Check for div</button> <button onclick=" var div = document.createElement('div'); div.id = 'newDiv'; document.body.appendChild(div); ">Add div</button>
Click the "Check for" button and you will get false . Add the div by clicking the "Add div" button and check again: you will get true .
source share