HTML:
<div id="foo">some content</div>
Javascript
var foo = document.id('foo'); // or $ but should be avoided due to conflicts // if it returns an Element object, it will be truthy. if (foo) { // code for when it exists } else { // code for when it does not. }
by the way, this mimics the behavior of the return value of document.getElementById , which is vanilla js. this may be true for any selector that is designed to return a single element, for example document.getElement('div.login > a.active') - it does not have to be by identifier only.
source share