Check if element exists – selenium / javascript / node-js


I’m trying to check if an element exists before I can execute this line:


This throws an error “no such element” if the id test doesn’t exist in the document, even in a try-block.
I’ve found answers for Java, where you can check if the size is 0, but in node-js this throws an error before I can check the size.

throw error;
NoSuchElementError: no such element


You can leverage the optional error handler argument of then().

driver.findElement('test')).then(function(webElement) {
        console.log('Element exists');
    }, function(err) {
        if (err.state && err.state === 'no such element') {
            console.log('Element not found');
        } else {

I couldn’t find it explicitly stated in the documentation, but determined this from the function definition in webdriver/promise.js in the selenium-webdriver module source:

   * Registers a callback on this Deferred.
   * @param {Function=} opt_callback The callback.
   * @param {Function=} opt_errback The errback.
   * @return {!webdriver.promise.Promise} A new promise representing the result
   *     of the callback.
   * @see webdriver.promise.Promise#then
  function then(opt_callback, opt_errback) { 

Answered By – Aaron Silverman

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published