Kyrgios Kyrgios - 3 months ago 9
Javascript Question

Getting data from ul li div and storing into json

I have think about this for last few hours and can't find any solution. So basically I have a list like this

<ul class="list">
<li class="user">
<div class="name">Name</div>
<div class="surname">Surname</div>
</li>
<li class="user odd">
<div class="name">Name</div>
<div class="surname">Surname</div>
</li>
<li class="user">
<div class="name">Name</div>
<div class="surname">Surname</div>
</li>
<!--And like so....-->
</ul>


And this is how my nightwatch script looks

.elements('css selector','.li',function(result){
console.log(result.value);
});


the result is [] = empty array

But the main question is what would be the best practice to execute the all the data in ul li div and write console.log like a json file?

Like :

{
"name": "name",
"surname": "Yaya",
},
{
"name": "name2",
"surname": "Yaya2",
},


Please If any of you can help, give me some handicap for this.

Answer

May be you can do something like the following in pure JS.

var lis = document.querySelectorAll("ul li"),
      i = 0,
  jData = [];
for (var li of lis) {
  var divs = li.getElementsByTagName("div"),
     liObj = {};
  for (var div of divs) liObj[div.className] = div.textContent;
  jData.push(liObj);
}
jData = JSON.stringify(jData);
console.log(jData);
  <ul class="list">
    <li class="user">
      <div class="name">Name</div>
      <div class="surname">Surname</div>
    </li>
    <li class="user odd">
      <div class="name">Name</div>
      <div class="surname">Surname</div>
    </li>
    <li class="user">
      <div class="name">Name</div>
      <div class="surname">Surname</div>
    </li>
  </ul>