Search code examples
javafacebookselenium-webdriverautomationfocus

Get ID, Class of Currently Focused Element in Selenium


There are many ways to select or focus an element in Selenium, for example using TAB key we can focus on next element. But, is there any way in Selenium to get all details of current focused element such as id, class, href, text etc ? i want to focus on Like, Comment or Share button of a post https://www.facebook.com/pitbull/photos/a.440436327400.230702.95051637400/10153236215477401/?type=3&theater of Facebook page of Pitbull, But nothing works for me, i tried xpath, class, id but unable to Focus on share button. i can focus on share button using Tab key about 161 times but how will i confirm that focused element is "Share" button or somethong else? ;) Here is my sample code

WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.findElement(By.id("email")).click();
driver.findElement(By.id("email")).sendKeys("[email protected]");
driver.switchTo().activeElement().sendKeys(Keys.TAB);

after TAB key, you know focus will be go to Password field from email field, so how can i get id, class or other details of focused element in my selenium code? in my example it is Password field.


Solution

  • You can use

    WebElement activeElement = driver.switchTo().activeElement(); 
    String className =  activeElement.getAttribute("class"); 
    String id = activeElement.getAttribute("id");