Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery element selector with Id from Selenium 2 / WebDriver

I can get an element's ID in Selenium with ((RemoteWebElement) webElement).getId(), which returns a string like this:

{e9b6a1cc-bb6f-4740-b9cb-b83c1569d96d}

I wonder about the origin of that ID. I am using the FirefoxDriver(), so is this Firefox related maybe?

Is there a way to select an element with Jquery only by knowing this ID?

like image 210
Alp Avatar asked Apr 10 '11 19:04

Alp


2 Answers

You don't need to access the internal ID at all. Just pass the WebElement instance to JavascriptExecutor.executeScript:

import org.openqa.selenium.JavascriptExecutor;

((JavascriptExecutor) driver).executeScript("$(arguments[0]).whatever()", myElement)
like image 118
jarib Avatar answered Sep 19 '22 22:09

jarib


This lots-of-letters-and-digits ID is an internal identifier of a node in the browser DOM that correspond to your WebElement object.

To get the value of the attribute 'id' you have to use getAttribute method:

String id = myElement.getAttribute("id");

To select an element by its 'id' attribute you have to use findElement method as follows:

WebElement myElement = driver.findElement(By.id("my_element_id"));

If you want to use jQuery selectors, you have to use findElement method as follows (suppose you know it is a 'div' element):

WebElement myElement = driver.findElement(By.cssSelector("div#my_element_id"));
like image 32
Alexei Barantsev Avatar answered Sep 19 '22 22:09

Alexei Barantsev