tags:

views:

198

answers:

3

The title says it all.

How do I test which element has the focus in Selenium RC?

+1  A: 

Hi hwiechers,

You can use CSS selectors when providing an element locator to Selenium: http://release.seleniumhq.org/selenium-core/1.0/reference.html#locators

Therefore, you can use the :focus CSS pseudo-class on your selector to only match if the element is focused.

Combine that with a verifyElementPresent action and a target of something like the following: css=.yourclassname:focus. Replace yourclassname with your CSS class name, of course, or use one of the other CSS selectors; the important bit is the :focus at the end.

Note that this will almost certainly not work in the Selenium IDE Firefox plugin. I imagine that is because this plugin will have focus instead. I couldn't get it to work in the IDE (test always failed), but it worked fine once I exported it and ran it as a Java test.

HTH

Sam

Sam
I'm marking this as the answer since it aught to work but I couldn't actually get it to work for me. I'm using selenium RC, I can see that the element is focused (because I added a *:focus { background: pink } to my css), but isElementPresent always returns false.
hwiechers
A: 

i am also meet the problem, help me. msn /mail: [email protected]

david-shang
+1  A: 

I couldn't get the :focus pseudoclass idea to work, not sure why - targeting "css=#search_input input.text" matched, but "css=#search_input input.text:focus" didn't? But here is what worked for me:

self.assertEquals(self.se.get_element_index('dom=document.activeElement'), self.se.get_element_index('//input[@id="search-query"]'))

This is using the Python Selenium API, so the get_element_index() calls are wrappers around the core Selenium command list. Adapt this to your environment. It's evaluating the element index of the document's focused element (gotten with a Javascript DOM locator) and the element index of the element you want to test for focus (gotten with an XPath locator.) Also see this question.

ari
Unfortunately get_element_index only gets the element's index within its parent. So if you have, say, two divs A and B, each of which contains a textfield as its only child, then if A's textbox is selected, both of the get_element_index calls in your example code will return 0 so you'll get a false positive.
Giles Thomas