How to put all elements' content in array using jQuery ?

后端 未结 2 1273
时光说笑
时光说笑 2020-12-04 00:34

Text1

Text2

Text3

Result should be :

[         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 00:59

    jQuery provides .map() for this:

    var items = $('#main p').map(function () { return $(this).text(); }).get();
    

    .map() iterates over its elements, invoking a function on each of them and recording the return value of the function in a new array, which it returns.

    You could also have solved this with a simple .each():

    var items = [];
    
    $('#main p').each(function (i, e) {
      items.push($(e).text());
    });
    

提交回复
热议问题