8

If I have the following HTML:

<ul>
  <li>List 1</li>
  <li>list 2</li>
  <li>list 3</li>
</ul>

Can I get the text content from the the <li>'s and place them in array using javascript?

JP Silvashy
  • 46,977
  • 48
  • 149
  • 227
sea_1987
  • 2,902
  • 12
  • 44
  • 69

2 Answers2

50
var arr = $("li").map(function() { return $(this).text() }).get();
  • The map()(docs) method creates a jQuery object populated with whatever is returned from the function (in this case, the text content of each <li> element).

  • The get()(docs) method (when passed no argument) converts that jQuery object into an actual Array.

user113716
  • 318,772
  • 63
  • 451
  • 440
Luke
  • 8,235
  • 3
  • 22
  • 36
  • 1
    What purpose does the `.get()` serve? – jlmakes Jan 31 '11 at 21:32
  • @Luke - I understand `.get()` returns the DOM element underneath the jquery, but what would the above code turn into without the `.get()`? – jlmakes Jan 31 '11 at 21:39
  • 1
    no it doesnt return the dom element, since we are not mapping a dom element. and btw, if there is no parameter in "get()" it returns the whole array. In this case, an array of the "text" value. – Luke Jan 31 '11 at 21:42
  • 1
    but the "get" is not requested, it just makes an basic array out of an jquery array. after mapping, you could use other jquery methods on it. Since the user with the question wants an array, we are giving him the basic array, without jquery – Luke Jan 31 '11 at 21:43
  • I knew there had to be a "nerd friendly" way to do this, this scratches my nerd itch +1 – SeanDowney Aug 15 '12 at 19:13
4
var x = [];
$("ul li").each(function() {
  x.push($(this).text());
});

or simply:

var x = $.map($("ul li"), function( i ) { return $(i).text(); });
KARASZI István
  • 30,900
  • 8
  • 101
  • 128