5

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?

Alp
  • 29,274
  • 27
  • 120
  • 198

2 Answers2

8

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)
Community
  • 1
  • 1
jarib
  • 6,028
  • 1
  • 24
  • 27
  • That's great, didn't knew about passing WebElements as arguments. Thanks alot :) Maybe you also know a solution for the "other direction": http://stackoverflow.com/questions/5490523/selecting-and-identifying-element-with-jquery-to-use-it-in-selenium-2-java-api – Alp Apr 11 '11 at 21:46
  • I have following HTML: I want to click the button by using jQuery in WebDriver with java. What's the exact code? – Ripon Al Wasim Aug 23 '12 at 09:31
2

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"));
  • Thanks, i know that. My question was maybe not clear enough. I want to use different selectors in Selenium like xpath or css selectors. If i found an element, there should be way to **create** a unique selector to use jquery to find the same element. My attempt was to use this internal identifier somehow, but i am not sure if there is a jquery/javascript way to use this id to find the according element. – Alp Apr 11 '11 at 18:53
  • Actually, WebElement is just a holder for this internal ID. But, AFAIK, these internal IDs will change as soon as the browser rebuild DOM tree. And if you try to use "old" WebElement (i.e. "old" ID) you'll get StaleElementReferenceException. – Alexei Barantsev Apr 11 '11 at 19:14
  • That's not a problem. I will use jQuery at the same DOM tree instance. Take it as a jquery wrapper for selenium. – Alp Apr 11 '11 at 19:24