108

I have a structure like this:

<ul>
  <li>text1</li>
  <li>text2</li>
  <li>text3</li>
</ul>

How do I use javascript or jQuery to get the text as an array?

['text1', 'text2', 'text3']

My plan after this is to assemble it into a string, probably using .join(', '), and get it in a format like this:

'"text1", "text2", "text3"'

6 Answers 6

147
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('", "') + '"';
Sign up to request clarification or add additional context in comments.

6 Comments

Does jQuery guarantee an order to the elements returned by the query? I would assume that the order returned is the same as the ordering in the DOM (ie text1, text2, text3), but I don't know what to look for in the documentation to see if this is true.
I've never seen it traverse the DOM in any other way that normal reading order. So although I can't prove it, I would bet the farm that it alwaays traverses the DOM top to bottom :)
Isn't $.each considered to have bad performance? If yes, is there any other way to do it?
How many list items do you have that this is an issue, @Daniel? Yeah, there are other ways to do the same thing (you could use $.map() to generate the array in one go), but they amount to the same thing.
@Shog9: I wish to push a dictionary to the list taking values from two different columns from each rows of a table. Isn't there easier way to do that? Thanks in advance.
|
74

Without redundant intermediate arrays:

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

See jsfiddle demo

8 Comments

You miss .get() at the end.
Based on Felix Klings suggestion: arr = $('li').map(function(){ return $(this).text(); }).get();
i dont understand why "get function" is necessary.
api.jquery.com/map explains why there's a .get() necessary ("As the return value is a jQuery-wrapped array, it's very common to get() the returned object to work with a basic array.").
The worse thing is, that the iterator is wrong, you need to switch the element and index, so that it says function(i, el).
|
15

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);

Comments

14

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(', ');

3 Comments

I just saw this here (stackoverflow.com/questions/4856283/…) and was gonna repost since it's a great trick to know
My way should be little bit faster.. or not?
kimstik, according to Benchmark.js, my function call does 11,252 / 9,685 ops/sec for Opera and Chrome respectively, whereas the method call you posted does 9,666 / 9,083 ops/sec on a list of 40 items. I think the difference comes from the conversion from jQuery element list to Array in your example, if that helps. They're very close, so pick whichever suits your coding style better :)
6
var arr = new Array();

$('li').each(function() { 
  arr.push(this.innerHTML); 
})

3 Comments

Instead of relying on innerHTML, you should change "this" to a jQuery object and use the jQuery native text method. $(this).text()
why? eventually $(this).html() will use the native method
In this case it's better to use [] instead of the new Array() - What’s the difference
4

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.