1

How can I check if an element exists in selenium?

I have tried:

browser.driver.findElements(by.id('my-id'))

but it does not seem to work.

5 Answers 5

5

Use isElementPresent

browser.driver.isElementPresent(by.id('my-id'))

or isPresent

element(by.id('my-id')).isPresent()
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is looking for an element that does not exist throws an exception. You ar eon the right track with using findElements as this will not throw an error if it cannot find the element, the problem you have is being left with a list that contains the elements found but not comparing to make sure that there is at least 1 element in the list (e.g. it found one element)

public boolean exists(By by){
return !driver.findElements(by).isEmpty(); 
}

is a function that will return true if it exists, false otherwise. Its clear from this method how you could modify it to suit your need.

3 Comments

Thanks Paul, +1. Isn't this java though?
Ahh I didn't see it said javascript, sorry!
@BarnabasSzabolcs Have you tried if (browser.driver.findElements(by.id('id')).size != 0) { ... } ?
1

webdriver.js example

In this example I am waiting for a modal to exist because its a modal that fades in

See the line that reads const doesModalFadeInExist = await this.driver.executeScript('return document.getElementsByClassName("modal fade in")');

You can put this line of code in a wait that waits for the element array to be >=1

This way you know it is there after checking inside the wait.

We can also check opacity at the same time.

Once the element array >=1 and opacity = '1' . then we exit the wait and continue the test

async waitForModalFadeIn() {
        try {
          let isVisible;
          let opacityReturned;
          let isModalFadeInFound;
          const dialog = await this.driver.wait(until.elementLocated(this.baseselector.MODAL_FADE_IN));
          await this.driver.wait(async () => {
            const doesModalFadeInExist = await this.driver.executeScript('return document.getElementsByClassName("modal fade in")');
            isModalFadeInFound = doesModalFadeInExist;
            const bool = await this.isDisplayed(this.baseselector.MODAL_FADE_IN);
            isVisible = bool;
            const opacity = await dialog.getCssValue('opacity');
            opacityReturned = opacity;
            return isVisible === true && isModalFadeInFound.length > 0 && opacity === '1';
          }, 4000);
          return opacityReturned === '1' && isVisible === true && isModalFadeInFound.length > 0;
        } catch (err) {
          console.log(`Function waitForModalFadeIn: Failed to open modal${err}`);
          return null;
        }
      }

Example Test

    it('Trigger "unmetered" modals in the technical spec section', async () => {
        await wHost.visit(page = '/web-hosting');
        const table = await driver.wait(until.elementLocated(wHost.selector.COMPETITOR_TABLE), this.pageLoadTimeOut);
        await driver.executeScript('arguments[0].scrollIntoView()', table);
        const modals = await table.findElements(wHost.selector.UNLIMITED_MODAL);
        for (let i = 0; i < modals.length; i++) {
          await modals[i].click();
          assert.isTrue(await common.waitForModalFadeIn());
          assert.isTrue(await common.closeModal());
        }
      }); 

Comments

1

This is what you are looking for, This function takes id as parameter, If the element is found it returns json object with status=true and element you were looking for.

async function ElementExistsID(element){
    return new Promise(async (resolve)=>{
        try{
            let ElementResult=await driver.findElement(webdriver.By.id(element));
            resolve({"element":ElementResult,"status":true});
        }
        catch(error){
            log.warn(error);
            resolve({"status":false});
        }
    })
}

You can use it like this

let ElementIamLookingFor=await ElementExistsID(IDOfTheElement);
if(ElementIamLookingFor.status){
    console.log("Element exists");
}
else{
    throw new Error("Element not found");
}

1 Comment

+1, for effort, it looks legit. I'll get back to this once I'll have to do webdriver things again. Please note that variables and functions in JS usually start with a lowercase character as opposed to object generators (aka class types in other languages).
0

After many attempts, the following worked for me:

function doIfPresent(elementId, doIfPresent, next) {
  var elem = by.id(elementId);
  browser.driver.isElementPresent(elem).then(function (present){
    if (present) {
      doIfPresent(element(elem));
    }
    next();
  });
}

eg.

doIfPresent('my-button', function(element){ element.click();}, function(){
  // your code continues here
});

I don't get it though why we'd need to use futures here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.