javascriptjquerylistviewdata-collection

How to collect data from a list and export it as raw text


I'm stuck putting things together by JavaScript/jQuery.

Here is my HTML:

<ul id="container">
  <li><span class="spName">insalata mista</span>
    <p class="spPr"><span class="zPr">6,90</span> €</p>
    <p class="spPrExtra"><span class="spName">+Parmesan</span> <span class="zPr">1,50</span></p>
    <p class="spPrExtra"><span class="spName">+Mozzarella</span> <span class="zPr">2,00</span></p>
  </li>
  <li><span class="spName">spaghetti al sugo</span>
    <p class="spPr"><span class="zPr">8,20</span></p>
    <p class="spPrExtra"><span class="spName">+Champignons</span> <span class="zPr">1,00</span> €<br></p>
  </li>
</ul>

I need an output of raw text, collecting the parts out of the list with a result like that:

insalata mista 6,90
+Parmesan 1,50
+Mozzarella 2,00
spaghetti al sugo 8,20
+Champignons 1,00

Any help welcome!


Solution

  • This is what you have to do to get the text of each .spName and .zPr using a jQuery .each function in li first and then from there .each all the p to get the desired text and data via their .children and class-names

    Read more about .each jQuery function here

    Read more about .children jQuery function here

    I have also changed your HTML a little bit as it was correctly added and to each elements and span.

    Run snippet below to see it working.

    $('li').each(function() {
      $(this).children('p').each(function() {
        $('#plain_text').append($(this).children('.spName').text() + ' ' + $(this).children('.zPr').text()+'<br>')
      })
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul id="container">
      <li>
        <p>
          <span class="spName">insalata mista</span><span class="zPr">6,90 €</span> €</p>
        <p><span class="spName">+Parmesan</span> <span class="zPr">1,50</span></p>
        <p class="spPrExtra"><span class="spName">+Mozzarella</span> <span class="zPr">2,00</span></p>
      </li>
      <li>
        <p><span class="spName">spaghetti al sugo</span><span class="zPr">8,20</span></p>
        <p class="spPrExtra"><span class="spName">+Champignons</span> <span class="zPr">1,00</span> €<br></p>
      </li>
    </ul>
    
    
    <div id="plain_text"></div>