Suppose I want to get all text of each li
and save it into an array, how m开发者_JAVA百科ight I do that.
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"]
Give the <ul>
an id and something like
$("#yourulid li").map(function(){
return $(this).text();
}).get().join(',');
See a working demo
For more details take a look at
jQuery.map()
and .get()
If you want to get the text as a comma separated string then only you need to use .join()
.
Use the jQuery .map() function.
$('li').map(function(){
return $(this).text();
});
Edit: As pointed out by @rahul I wrapped "this" in a jQuery object.
you will have to use each to iterate over li list first and then put every text in an array.
var arr=[];
$("li").each(function(n){
arr[n] = $(this).text();
});
var myArray = [];
$("ul").children().each(function(index) {
myArray[index] = $(this).text();
});
The crude and inelegant way of doing it:
var output = [];
$('#your-ul li').each(function()
{
output.push($(this).text());
});
精彩评论