从javascript(nightwatch.js)的下拉菜单中选择随机值

时间:2018-09-04 08:37:26

标签: javascript nightwatch.js

没有太多的javascript或nightwatch.js经验,所以很抱歉这样做。

我有一个随机填充的下拉菜单。

我想做的是随机选择这些下拉菜单选项之一。

下拉菜单的html如下;

enter image description here

我只想从列表中选择一个条目(当然,下一次加载该元素会改变-包括条目和名称的数量-下次加载该元素)。

我有一个有效的 ruby​​ 脚本;

modelrangeselect = @driver.find_element(:id, 'listRange_ddlItems')
carmodelrange = modelrangeselect.find_elements(:tag_name => 
'option').sample

但是我无法确定 javascript 的等效含义,因此我可以在nightwatch.js上运行它。

任何帮助将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:0)

我认为这足以随机选择一个选项,代码应具有自我解释性:)。

 // get the dropdown element
 const select  = document.getElementsByClassName('url-dropdown');

 // fetch all options within the dropdown
 const options = select.children;  

 // generate a random number between 0 and the total amount of options
 // the number will always be an index within the bounds of the array (options) 
 const random  = Math.floor(Math.random() * options.length);

 // set the value of the dropdown to a random option
 select.value = options[random].value;