using By.js selector with webdriver JavaScript

Recently got a request for automation POC with JavaScript and selenium webdriver. One issue I ran into is trying to match text of a button as the criteria to locate the object on page. Don’t want to use xpath but can’t use css as there is no “text()=”. At the end, I use the By.js selector and “contains” to solve this problem. Here’s an example:


driver.findElement(webdriver.By.js("return $(\'button:contains(\"Save\")\');")).then(function(button) {
            button.click();
        });

From there, you can easily extract a function out of this so you can apply it to all of your By.js locator:


/**
* replace the findElement with getElementByText
*
* driver.findElement(webdriver.By.js("return $(\'button:contains(\"Save\")\');")).then(function(button) {
*     button.click();
* });
**/
getElementByText('button', 'Save').then(function(ele) {
    ele.click();
});

function getElementByText(baseLocator, text) {
    return driver.findElement(webdriver.By.js("return $(\'" + baseLocator + ":contains(\"" + text + "\")\');"));
}

One note, make sure you have the “return” in the javascript code explicitly or you will see the following error:


TypeError: Custom locator did not return a WebElement