如何使用Mootools通过id检查元素是否存在

Aad*_*adi 4 mootools

如何使用Mootools通过id检查元素是否存在

Dim*_*off 9

HTML:

<div id="foo">some content</div>
Run Code Online (Sandbox Code Playgroud)

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.
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,这模仿了返回值为document.getElementByIdvanilla js的行为.对于任何意图返回单个元素的选择器都可以,例如document.getElement('div.login > a.active')- 不需要仅通过ID.