Kalef Kalef - 4 months ago 55
Javascript Question

How can i getText from li items, inside ol element with Nightwatch.js?

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.

Answer

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.

Comments