How ByChained works in selenium

In this blog post let us understand what is ByChained class.

Introduction to ByChained class in selenium

In Selenium API ByChained is a predefined class which is part of package org.openqa.selenium.support.pagefactory

The ByChained class has a constructor which takes variable arguments of type By instance so that you can pass multiple instances of By

Working of ByChained object

Using ByChained object we can find the elements that are matched by the first argument, then their descendant using the subsequent parameters.

HTML Code to automate

<html>
  <body>
    <div id="div-01">
      <input type="text" id="user-name-txt-field"/>
    </div>
    <div id="div-02">
      <input type="text" id="user-name-txt-field"/>
    </div>
  </body>
</html>

We need to write a code to locate user-name-txt-field which is inside div whose id is div-01.

Program demonstrating without ByChained class

Without using ByChained class we would have achieved like

WebElement div01Elmnt = driver.findElement(By.id("div-01"));
WebElement userNameTxtElmnt = div01Elmnt.findElement(By.id("user-name-txt-field"));
userNameTxtElmnt.sendKeys("Naveen");

Program demonstrating by using ByChained class

The same thing can be achieved using ByChained class by writing more efficient code and elegant code as shown below:

WebElement userNameTxtElmnt = driver.findElements(new ByChained(By.id("div-01"),By.id("user-name-txt-field")  ));
userNameTxtElmnt.sendKeys("Naveen");

 


About the course

NPN Training is counted among the top ten selenium training centers in Bangalore for providing the best Selenium training in Bangalore. Our selenium course content and syllabus is designed according to the student’s requirement to accomplish everyone’s career goal.

Naveen P.N

12+ years of experience in IT with vast experience in executing complex projects using Java, Micro Services , Big Data and Cloud Platforms. I found NPN Training Pvt Ltd a India based startup to provide high quality training for IT professionals. I have trained more than 3000+ IT professionals and helped them to succeed in their career in different technologies. I am very passionate about Technology and Training. I have spent 12 years at Siemens, Yahoo, Amazon and Cisco, developing and managing technology.