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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

What purpose does the .get() serve?
@Luke - I understand .get() returns the DOM element underneath the jquery, but what would the above code turn into without the .get()?
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.
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
I knew there had to be a "nerd friendly" way to do this, this scratches my nerd itch +1
4
var x = [];
$("ul li").each(function() {
  x.push($(this).text());
});

or simply:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.