views:

12240

answers:

3

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"'
+12  A: 
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('", "') + '"';
Shog9
+1  A: 
var arr = new Array();

$('li').each(function() { 
  arr.push(this.innerHTML); 
})
Dave Ward
Instead of relying on innerHTML, you should change "this" to a jQuery object and use the jQuery native text method. $(this).text()
Nathan Strutz
why? eventually $(this).html() will use the native method
Kheu
+1  A: 

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