This article assumes you have a driver initialized.
There are 2 ways to check if an element exists with WebDriverJS:
findElement
You can use findElement to check if NoSuchElementError
is thrown:
driver
.findElement({
className: 'nonexistent-class',
})
.catch((error) => {
if (error.name === 'NoSuchElementError') {
// handle when element is not found
}
});
Note: This can also be written with then
instead of catch
:
driver
.findElement({
className: 'nonexistent-class',
})
.then(null, (error) => {
if (error.name === 'NoSuchElementError') {
// handle when element is not found
}
});
findElements
You can use findElements to check if the length of elements is 0:
driver
.findElements({
className: 'nonexistent-class',
})
.then((elements) => {
if (elements.length === 0) {
// handle when element is not found
}
});