4

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

halfer
  • 19,824
  • 17
  • 99
  • 186
david-shang
  • 101
  • 2
  • 3
  • 10

4 Answers4

5

The following locator should select the active element in the document:

dom=document.activeElement

If a form field or similar element has focus, then it should be the active element. Hope this helps.

AlistairH
  • 3,139
  • 2
  • 21
  • 19
  • i use the following code, but can not get value. String searchValue=selenium.getEval("var test=document.activeElement.id;"); – david-shang Jun 29 '10 at 09:01
  • Thank you, that's the trick. Sorry but it took me a while to find it--once I knew I was looking for activeElement everything else was easy! – Bill K Sep 20 '11 at 22:55
  • Just heads up, in selenium webdriver its `driver.switch_to.active_element` – wamster Feb 08 '21 at 06:58
3

As AlistairH mentions, you can use document.activeElement on most current browsers. To use this in Selenium you can store the active element and compare it to the active element. Below is an example for Selenium IDE, which should point you in the right direction for Selenium RC too.

storeEval | this.browserbot.findElement("name=targetElement").id; | targetElement
storeEval | this.browserbot.getUserWindow().document.activeElement.id; | activeElement
verifyEval | '${targetElement}' | ${activeElement}

Note that the above relies on the element having a unique id assigned.

Dave Hunt
  • 8,191
  • 4
  • 38
  • 39
2

Another way to test (assuming you are using JQuery or Sizzle) is to use a simple library I wrote which allows Selenium tests to query the DOM using the :focus selector such as .is(':focus') or $(':focus').

For more information, see http://blog.mattheworiordan.com/post/9308775285/testing-focus-with-jquery-and-selenium-or where I explain the reason why Selenium test for :focus don't work out of the box, and how to fix this.

Matthew O'Riordan
  • 7,981
  • 4
  • 45
  • 59
0

source code:

<div class="box_container">
    <input type="text" value="" name="to_hidden" id="to:12982f12165_hidden" class="left_to_right" autocomplete="off" style="display: none;">
    <textarea id="to:12982f12165" name="to" style="overflow: hidden; height: 18px;" class="left_to_right" autocomplete="OFF">
    
    </textarea>
</div>

selenium code: 1 method:

String searchValue=selenium.getEval("var test=document.activeElement;");

2 method:

String testvalue=selenium.getText("css=#div textarea[class='left_to_right']:focus");    
MaxiGui
  • 6,190
  • 4
  • 16
  • 33
david-shang
  • 101
  • 2
  • 3
  • 10