Nikul Panchal
Nikul Panchal

Reputation: 1673

Unable to locate element error in selenium webdriver node.js

I have put an if else condition in selenium webdriver node.js to check if a string contains an "Add New" string, but I am getting the error Unable to locate element: // *[contains(text(),'Add New')]

Here is the code:

    if (driver.findElement(By.xpath("// *[contains(text(),'Add New')]"))) {
        reject(new Error("This is an error"));
    } else {
        resolve(true);
    }

Upvotes: 0

Views: 228

Answers (1)

Jeni
Jeni

Reputation: 1118

Try this one

 string bodyText = driver.findElement(By.xpath("//body")).text;
 if (bodyText.Contains('Add New')) {
      reject(new Error("This is an error"));
  } else {
      resolve(true);
  }

Or

try {
    driver.findElement(By.xpath("// *[contains(text(),'Add New')]"));
    reject(new Error("This is an error"));
}
catch (ElementNotFound e) {
    resolve(true);
}

Note: the first one should be significantly faster, since the second approach would try to wait for implicit wait amount of time before it throws the error for the element not being found.

Upvotes: 1

Related Questions