Stale Element when using PageFactory – Selenium

Photo by luis gomes on

Hello guys,

The first post of the year will be a quick one. Took me a while to figure out since it has been ages I coded in Selenium/Java and used PageFactory (which I thought was deprecated, but it is just deprecated in C#)

If you ever come across an error like this when using PageFactory:

stale element reference: element is not attached to the page document

PageFactory initializes the elements the first time you run the automation and when the page changes (which happens on Angular and React pages) Selenium loses the reference to that element and needs to find it again with the new DOM.

You can do something like this:

protected void clickElement(WebElement element) {
   try {
   } catch (StaleElementReferenceException e) {
       PageFactory.initElements(driver, this);

2 thoughts on “Stale Element when using PageFactory – Selenium

  1. Thanks for the article. I found your blog by searching “when not to use PageFactory” as I’m getting the strong feeling that PageFactory isn’t the best option for my current project. Then I started wondering if there are some newer automation tools out there that I should consider using instead of Selenium. So I was curious when you said you haven’t used Selenium and PageFactory in ages. What were you using for automation?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.