Thursday, September 21Be an Automation Engineer

Find elements using javascript in protractor

There are many element location strategies available in protractor. Click here to know about element locators in protractor.

by.js is one more element locating strategy available in protractor. We need to pass javascript code as a string or as a function to by.js to get single/multiple element(s).

Pass javascript code as a string:
  • Identify single element
    var myWebElement = element(by.js("return document.getElementById('id1');");
  • Identifying multiple elements
    element.all(by.js("return document.getElementsByTagName('h1');").then(function(myWebElements){
    //your code
    });
Pass javascript code as a function:
  • Identifying single element
    var myWebElement = element(by.js(function(){
    return document.getElementById('id1');
    }));
  • Identifying multiple elements
    element.all(by.js(function(){
    return document.getElementsByTagName('h1');
    })).then(function(myWebElements){
    //your code
    });
    

Execute the below program to know more about by.js element locator.

describe('Locating elements using JS', function () {
    it('Locate H1 tags', function () {
        browser.get("http://angularjs.org");
        element.all(by.js(function () {
            //This is javascript code which will get h1 elements
            var elementsArray = new Array();
            var anchors = document.querySelectorAll('h1');
            for (var i = 0; i < anchors.length; ++i) {
                if (anchors[i].textContent != '') {
                    elementsArray.push(anchors[i]);
                }
            }
            return elementsArray;
        })).then(function (webElements) {
            //prints Number of h1 tags identified
            console.log(webElements.length);
            for (var i = 0; i < webElements.length; i++) {
                webElements[i].getText().then(function (text) {
                    //prints text of each H1 tag
                    console.log(text);
                    //Verifying the text of each h1 tag should not be empty
                    expect(text).not.toBe('');
                })
            }
        });
    });
});

Keep in mind:
  • The Javascript code that we execute in by.js should return a webelement(s).
  • Like browser.executeScript, the javascript code given in by.js is evaluated in the context of the page and cannot access variables from out test file.

Happy Testing!!!

%d bloggers like this: