The requirement is to get locator(By) of current web element.
For my project, I'm implimenting custom elements. So for a an HTML select element, there would be a class SelectElement and for an HTML option element, there would be class OptionElement.
To implement custom elements, I am using CustomWebElement
class from this repository: https://github.com/JulHorn/java_selenium_custom_elements
I would like to retrieve selectElementInstance.getOptions()
which should kind of return List<OptionElement>
and not List<WebElement>
.
So here is what I'm trying to do:
1) I am getting List<WebElement>
using findElements(...)
method.
2) In this list, I am iterating the element one by one.
3) Whichever WebElement
i get, i want to retrieve instance of By for this element.
4) With By instance in hand and WebDriver
instance already present, I can create custom element by using the constructor super(WebDriver driver, By by)
.
Below i have gave my code sample:
List<WebElement> myList = driver.findElement(By.xpath("//select[@id ='abcd']/*"));
ListIterator<WebElement> simpleChildIterator = myList.listIterator();
List<OptionElement> options = new ArrayList<OptionElement>();
while(simpleChildIterator.hasNext())
{
By l = simpleChildIterator.next().getBy();//I want locator for same element
//Here I can now create Instance of OptionElement to add to List<OptionElement>
OptionElement o = new OptionElement(driver, l);
options.add(o);
}
Please note that when I use OptionElement extends CustomWebElement
implementation in Page Object in lines with PageFactory
, the following works absolutely fine for me.
@findBy(xpath = "//select[@id ='abcd']/*")
List<OptionElement> options;
But this works because of PageFactory's magic that gets involved through its initElements()
call.
I want the same to work without PageFactory's involvement when I am willing to define a new method List<OptionElement> getOptions()
on my SelectElement
class.
I hope the question is clear now that I have made several edits.
Thanks to @Muzzamil for suggesting WebDriver should be singleton. I have removed that from my question. Also thanks to @Pranav to exemplify my issue with select and option elements. It is a better example to explain.