I have a structure like this:
- text1
- text2
- text3
Without redundant intermediate arrays:
arr = $('li').map(function(i,el) {
return $(el).text();
}).get();
See jsfiddle demo
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);
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
get children
get the array from toArray() method
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>
var arr = new Array();
$('li').each(function() {
arr.push(this.innerHTML);
})
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('", "') + '"';
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(', ');