When using Selenium, you have the ability to access the underlying DOM of the browser being manipulated through IWebElement instances. For example:
IWebElement domWrapper = driver.FindElement(By.Name("q"));
But what if you have the "domWrapper" instance but lack information on how the element was located or what it actually represents? Is it possible to assign an id to the element using Selenium under these circumstances? Most examples involve leveraging JavaScript and a locator to find the instance in the DOM.
My original question stated:
Is there a way to assign an id to an arbitrary element in Selenium when only having a reference through the IWebElement interface without knowledge of the element's unique identifier? While knowing that the driver can execute JavaScript, I am unsure how to uniquely refer to an element lacking an id.
Pseudo code example (this code locates the DOM element by utilizing a unique attribute, which I do not have in my case):
public string Id
{
get { return GetAttribute("id"); }
set
{
var finder = string.Format("document.querySelector('[{0}=\"{1}\"]')", "data-bind", element.GetAttribute("data-bind"));
string setId = "('id', '_id__'+(Math.floor(Math.random()*10000000)+1));";
string js = finder + ".setAttribute" + setId + ";";
Driver.ExecuteJavascript(js);
}
}