Get an array of list element contents in jQuery

JavascriptJquery

Javascript Problem Overview


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"'

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Without redundant intermediate arrays:

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

See jsfiddle demo

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

var arr = new Array();

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

Solution 6 - Javascript

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristian OudardView Question on Stackoverflow
Solution 1 - JavascriptShog9View Answer on Stackoverflow
Solution 2 - JavascriptkimstikView Answer on Stackoverflow
Solution 3 - JavascriptroenvingView Answer on Stackoverflow
Solution 4 - JavascriptCybolicView Answer on Stackoverflow
Solution 5 - JavascriptDave WardView Answer on Stackoverflow
Solution 6 - JavascriptNuOneView Answer on Stackoverflow