arguments[0].click() not working for select option

2019-03-22 05:23发布

I am using selenium for the web application automation.
I stuck in one point,I am using .ExecuteScript() to perform some action like to click on a link and for that am using :-

((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click()", driver.FindElement(By.XPath("//a[contains(text(),'Login to the Demo')]")));


[Note : for every click-able element am using ,this approach because click-able element may be hidden or not visible in web page] But this approach is not working for
<select> <option>item<option> .. </select>

I am using below code clicking on one of the select option :

((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click()", driver.FindElement(By.XPath("//select[@id='form_switcher']/option[5]")));

but nothing is happening nor giving any error/exception.

--Edit start--
But if I use without ExecuteScript() then its work fine:

driver.FindElement(By.XPath("//select[@id='form_switcher']/option[5]")).Click();

--Edit end--

[Note : I am using click to select options so that it fire the change event.]

So can anyone please explain me how to click on the select option using ((IJavaScriptExecutor)driver).ExecuteScript

Thanks in advance.

1条回答
我只想做你的唯一
2楼-- · 2019-03-22 05:48

For dropdowns you need to select and not click. You should return the element and then perform a element.SelectedIndex = 5;

If you need to modify your javascript to get the element via javascript instead of selenium you can utilize the document.evaluate located https://developer.mozilla.org/en-US/docs/Web/API/document.evaluate?redirectlocale=en-US&redirectslug=DOM%2Fdocument.evaluate

so then you return an element that represents your select element and then set the SelectedIndex value.

I believe this is correct...

((IJavaScriptExecutor)driver).ExecuteScript("var element = document.evaluate(\"//select[@id='form_switcher']\", document.documentElement, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); element.SelectedIndex = 5;  return element.fireEvent('event specifics go here')");

http://www.java2s.com/Code/JavaScript/HTML/UsingthefireEventMethod.htm

查看更多
登录 后发表回答