Reputation: 31
I have to do a little test tool using NW to get titles to an array, from a simple ol li elements..Ex: i need an array with : Coffe,Tea, Milk.
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Thanks for your cooperation in advance.
EDIT>>
Well, thanks to @SoftwareEngineer171 , I used .execute() to inject js to Nightwatch and is now running. This is the code i used and now working with array.. this code prints the number of li items of ol list (i used css selector anyway in this case) with @SoftwareEngineer171 code...
module.exports = {
'Demo' : function (client) {
client
.url('http://mylink.com/items')
.waitForElementVisible('body', 1000)
.execute(function(){
var arr = (function(a, b){
return (Array(a.length) + '').split(',').map(function(c, d){
return a[d].innerHTML;
});
})(document.getElementsByClassName("listing-view")[0].getElementsByClassName("listing-view-item"));
return arr;
}, ['arr'] ,function(result){
array_h1 = result.value
console.log(array_h1.length)
})
.pause(5000)
.end();
}
};
Upvotes: 1
Views: 1076
Reputation:
This solves your problem.
var arr = (function(a){
return (Array(a.length) + '').split(',').map(function(c, d){
return a[d].innerHTML;
});
})(document.getElementsByTagName('ol')[0].getElementsByTagName('li'));
EDIT
Ok, you requested explanation of this code, so here it is.
Firstly, we define anonymous
function which requires one argument (this is the first function in the code) and we pass argument document.getElementsByTagName('ol')[0].getElementsByTagName('li')
as variable a
which represents all of your <li>
elements. Now, a
is an object which has HTMLCollection
function as it's constructor, so it is not an array. To extract text from this collection, we must convert it to an array. This is the reason why we create new array and map each element from HTMLCollection
to our new array. The second function you see simply copy each element from HTMLCollection
object to array and then return array, as you wanted.
If it's still not clear to you what is constructor
, anonymous
function, array mapping, etc, I suggest you to read this article.
Upvotes: 2