Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium: Check if a WebElement has the focus

Tags:

I was expecting something like WebElement.isfocus(),... something really simple, but the only approach I found is using the

:focus  

pseudo class.

Is this really such an uncommon task as for not find tons of information?

I'm aware of this SO topic, but it's been almost two years from then. Nothing new in more recent versions?

Would you know some workaround?

like image 355
luso Avatar asked Jun 10 '13 13:06

luso


People also ask

How do you know if an element is focused in Selenium?

We can test if an element is focused with Selenium webdriver. This is determined with the help of the activeElement() method. First of all we need to identify the element with help of any of the locators like id, class, name, xpath or css.

How do you get focused elements in Selenium?

In Selenium 2.0, if you are using WebDriver to drive the tests in the browser, you can use the WebDriver. TargetLocator class to get the element in focus, in a window/frame: WebDriver driver = ... // initialize the driver. WebElement currentElement = driver.

How do you know if a WebElement contains text?

We can find an element that contains specific text with Selenium webdriver in Python using the xpath. This locator has functions that help to verify a specific text contained within an element. The function text() in xpath is used to locate a webelement depending on the text visible on the page.

Is getText () a WebElement method?

What Is getText() Method? The Selenium WebDriver interface has predefined the getText() method, which helps retrieve the text for a specific web element. This method gets the visible, inner text (which is not hidden by CSS) of the web-element.


2 Answers

There is another topic that covers this issue: Test if an element is focused using Selenium Webdriver

Basically the code will be

element.equals(driver.switchTo().activeElement()); 
like image 133
JacekM Avatar answered Oct 19 '22 08:10

JacekM


for python developers:

def is_element_focus(id):     return self.driver.find_element_by_id(id) == self.driver.switch_to.active_element 
like image 25
Bartłomiej Bartnicki Avatar answered Oct 19 '22 07:10

Bartłomiej Bartnicki