L84
L84

Reputation: 46308

.each and .text to store a variable?

I have some jQuery to loop through li elements of a div and grab the text of those elements.

I have tried this code:

var liText = $('#4441437 li').each(function() {  
   $( this ).text()
});

console.log(liText);

When I do this I see this:

Object[li, li, li, li, li, li, li, li, li, li]

I realize that this is a jQuery object that is returned.

My question is how do I store just the text in a variable for each li element within a div?

Upvotes: 0

Views: 130

Answers (3)

101
101

Reputation: 62

Try using this:

var liText = [];
 $('#4441437 li').each(function() {
    liText.push($( this ).text() 
 }); 
 console.log(liText);

Upvotes: 0

Levan Lotuashvili
Levan Lotuashvili

Reputation: 841

You can store text values in Array, or store all content in one variable as one string (not a good idea). I will post both versions:

var contentArr = [];
var fullContent = '';
var liText = $('#4441437 li').each(function() {  
    contentArr.push($(this).text());
    fullContent += $(this).text() + ' ';
});

console.log(contentArr);
console.log(fullContent);

Here is example in JSFiddle

Upvotes: 2

Alex Char
Alex Char

Reputation: 33218

Try this:

js

var liText = $('#4441437 li').map(function() {  
    return $( this ).text()
}).get();

console.log(liText);

fiddle

Upvotes: 4

Related Questions