How can I create an array from something like $ ("li"). Text ()

Suppose I want to get all the text of each liand store it in an array, how can I do this.

For example, something like ...

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
</ul>

should give me an array like

["1", "2", "3", ..., "10"]
+3
source share
5 answers

Give <ul>id and something like

$("#yourulid li").map(function(){
    return $(this).text();
}).get().join(',');

See working demo

See details

jQuery.map() and .get()

If you want the text to be separated by a comma, then you need to use . .join()

+7
source

you will need to use each to first iterate over the li list and then put each text into an array.

var arr=[];

$("li").each(function(n){

arr[n] = $(this).text();

});
+1
source

jQuery . map().

$('li').map(function(){
  return $(this).text();
});

: @rahul, "this" jQuery.

+1
var myArray = [];
$("ul").children().each(function(index) {
    myArray[index] = $(this).text(); 
});
+1

:

var output = [];

$('#your-ul li').each(function()
{
  output.push($(this).text());
});
0

All Articles