Let's say I have the following DOM structure, for simplicity:
<div class='myparent'>
<div class='child'>
<div class="label">A</div>
<div class="ico"/>
</div>
<div class='child'>
<div class="label">B</div>
<div class="ico"/>
</div>
<div class='child'>
<div class="label">C</div>
<div class="ico"/>
</div>
</div>
I would like to loop within all child
Element returned by the function findAllByCssSelector('.child'). In particular, I would click on the ico
div subelement ONLY if the label
of the div is B.
I would remember, that findAllByCssSelector()
returns Promise.<Array.<leadfoot/Element>>
.
Typically I should do something like:
var my_label = null;
this.remote
.findAllByCssSelector('.my-selector').then(function (elementArray) {
for(.....) {
elementArray[i]
.getVisibileText()
.then(function (text) {
if(text == my_label)
elementArray[i].findByCssSelector('.ico').click().end()
}
}
})
I tried this code but did not work, because the elementArray[i]
within the getVisibleText().then()
function does not exist - it's like I lose its reference. Furthermore, I need also that if the label is not found at the end of the loop, an exception should be thrown.
How can I achieve that? Could anyone help, please?
The simplest way to do this would be to use an Xpath expression to select the item directly, like:
.findByXpath('//div[@class="child" and div[@class="label" and text()="B"]]/div[@class="ico"]')
The expression above will find the first div with class "ico" that's the child of a div with class "child" that has a child div with class "label" and text content "B".
Update
Using an Xpath expression is almost always preferable to looping through elements using Leadfoot commands because it's significantly more efficient, but if looping is desired for some reason, you can do something like:
var my_label = null;
this.remote
.findAllByCssSelector('.my-selector')
.then(function (elementArray) {
return Promise.all(elementArray.map(function (element) {
return element.getVisibleText()
.then(function (text) {
if (text === my_label) {
return element.findByCssSelector('.ico')
.then(function (ico) {
return ico.click();
});
}
});
});
});
A couple of key points to note:
- You need to return Promises/Commands from
then
callbacks when you're performing async operations in thethen
callbacks - Element methods (like
element.findByCssSelector
) return Promises, not Commands, so you can't callclick
on the result.
来源:https://stackoverflow.com/questions/32272598/intern-loop-on-promise-array-leadfoot-element