javascript - jQuery each-loop access every index text element -


i have below snippet.

if run snippet able see output correct need store each span's text element in variable process further. if possible prefer solution without recursive function.

$(document).ready(function () {      $('li').click(function (e) {               let fo; let foo; let fooo;        $(e.currenttarget).children('span').each(function() {          console.log($(this).text());          // expected output          // fo = li1(2)   +span1          // foo = li1(2)  +span2          // fooo = li1(2) +span3        });      });  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div>    <ul>      <li>        <span style="display: block;">li1 + span1</span>        <span style="display: block;">li1 + span2</span>        <span style="display: block;">li1 + span3</span>      </li>      <li>        <span style="display: block;">li2 + span1</span>        <span style="display: block;">li2 + span2</span>        <span style="display: block;">li3 + span3</span>      </li>    </ul>  </div>

to achieve require build array of span texts using map(). method has advantage of being dynamic enough work number of child elements.

once you've built array can either loop on work values, or select specific instance index. try this:

$(document).ready(function() {    $('li').click(function(e) {      var textvalues = $(this).children('span').map(function() {        return $(this).text();      }).get();            console.log(textvalues[1]); // second item      console.log(textvalues); //    });  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div>    <ul>      <li>        <span style="display: block;">li1 + span1</span>        <span style="display: block;">li1 + span2</span>        <span style="display: block;">li1 + span3</span>      </li>      <li>        <span style="display: block;">li2 + span1</span>        <span style="display: block;">li2 + span2</span>        <span style="display: block;">li3 + span3</span>      </li>    </ul>  </div>


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -