<div id="foo">some content</div>
Run Code Online (Sandbox Code Playgroud)
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.
}
Run Code Online (Sandbox Code Playgroud)
顺便说一下,这模仿了返回值为document.getElementByIdvanilla js的行为.对于任何意图返回单个元素的选择器都可以,例如document.getElement('div.login > a.active')- 不需要仅通过ID.