Get an array of list element contents in jQuery

后端 未结 6 1327
日久生厌
日久生厌 2020-11-27 11:33

I have a structure like this:

  • text1
  • text2
  • text3

相关标签:
6条回答
  • 2020-11-27 11:49

    Without redundant intermediate arrays:

    arr = $('li').map(function(i,el) {
        return $(el).text();
    }).get();
    

    See jsfiddle demo

    0 讨论(0)
  • 2020-11-27 11:52

    And in clean javascript:

    var texts = [], lis = document.getElementsByTagName("li");
    for(var i=0, im=lis.length; im>i; i++)
      texts.push(lis[i].firstChild.nodeValue);
    
    alert(texts);
    
    0 讨论(0)
  • 2020-11-27 11:54

    You may do as follows. one line of code will be enough

    • let array = $('ul>li').toArray().map(item => $(item).html());
    • Get the interested element

      1. get children

      2. get the array from toArray() method

      3. filter out the results you want

    let array = $('ul>li').toArray().map(item => $(item).html());
    console.log(array);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
      <li>text1</li>
      <li>text2</li>
      <li>text3</li>
    </ul>

    0 讨论(0)
  • 2020-11-27 11:59
    var arr = new Array();
    
    $('li').each(function() { 
      arr.push(this.innerHTML); 
    })
    
    0 讨论(0)
  • 2020-11-27 12:02
    var optionTexts = [];
    $("ul li").each(function() { optionTexts.push($(this).text()) });
    

    ...should do the trick. To get the final output you're looking for, join() plus some concatenation will do nicely:

    var quotedCSV = '"' + optionTexts.join('", "') + '"';
    
    0 讨论(0)
  • 2020-11-27 12:03

    kimstik was close, but not quite.

    Here's how to do it in a convenient one-liner:

    $.map( $('li'), function (element) { return $(element).text() });
    

    Here's the full documentation for jQuery's map function, it's quite handy: http://api.jquery.com/jQuery.map/

    Just to answer fully, here's the complete functionality you were looking for:

    $.map( $('li'), function (element) { return $(element).text() }).join(', ');
    
    0 讨论(0)
提交回复
热议问题