e1che
e1che

Reputation: 1251

Set focus on WebElement?

i'm currently testing the GUI of my application, and i wanted to know if it's possible to set the focus to a WebElement ?

I'm using Selenium 2.0 and the webdriver.

So i'm looking for something like that : driver.findElement(xxxx).setfocus();

Thank you.

EDIT : I've alreardy tested that kind of tricky things

// getting the element WebElement 
eSupplierSuggest = driver.findElement(By.xpath("..."));

//get le location and click 
Point location = eSupplierSuggest.getLocation();
new Actions(driver).moveToElement(eSupplierSuggest, location.x, location.y).click();

//or

//directly perform
new Actions(driver).moveToElement(eSupplierSuggest).click().perform();

i red somewhere that the click focus the element, but in my case, nothing works. lol

PS : this is a sub-question of that original post Click on a suggestbox, webdriver

Upvotes: 1

Views: 34225

Answers (5)

Mandy
Mandy

Reputation: 475

In order to set focus on the element you can use executeScript method as described below :

JavascriptExecutor js;
js.executeScript ("document.getElementById('x').focus()");

Once the focus is set you can easily use send_keys provided by webdriver api.

Upvotes: 2

Nora
Nora

Reputation: 1482

I normally send an empty key to the element so it gets focused. So for example:

element.send_keys ""

Upvotes: 6

buddy
buddy

Reputation: 183

Make sure, that you are not changing the frame.... Other wise .click() should do the trick

Upvotes: 0

Ardesco
Ardesco

Reputation: 7441

There is no function in the WebDriver API to set focus on an element.

If you want to do it you would have to write some JavaScript to set focus and then use a JavaScriptExecutor to run the JavaScript.

Upvotes: 0

HemChe
HemChe

Reputation: 2337

Try using cssSelector for the autosuggestion click as shown below and let me know if you are still facing the issue.

 // supplier ops, i find and type data into the input
    WebElement eSupplier = driver.findElement(By.id("supplier:supplierOps_input"));
    eSupplier.sendKeys("OPS1");
    sleep(5); // wait the suggestbox

    // i find the suggestbox
    WebElement eSupplierSuggest = driver.findElement(By.cssSelector("css path of that specific value in the auto suggestion box"));
    eSupplierSuggest.click();
    sleep(5); // wait the refresh for the next field supplierAddress

Upvotes: 0

Related Questions