sea_1987
sea_1987

Reputation: 2954

jquery collect value of list items and place in array

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?

Upvotes: 8

Views: 15825

Answers (2)

Luke
Luke

Reputation: 8407

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.

Upvotes: 50

KARASZI Istv&#225;n
KARASZI Istv&#225;n

Reputation: 31477

var x = [];
$("ul li").each(function() {
  x.push($(this).text());
});

or simply:

var x = $.map($("ul li"), function( i ) { return $(i).text(); });

Upvotes: 4

Related Questions