amateur
amateur

Reputation: 44673

Put all element values in an array

I have the following markup:

<div class="class1"><p>line1</p><p>line 2</p></div>

With jQuery, how can I take the values of all the p tags within the div and place them in an array?

Upvotes: 3

Views: 353

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

I will assume you mean the contents of the <p> elements, not their value (which is nothing).

var text = [];
$('.class1 > p').each(function() {
    text[text.length] = $(this).text();
});

Upvotes: 2

David Tang
David Tang

Reputation: 93714

Use .map():

var arr = $('.class1 p').map(function () {
    return $(this).text();
}).get();

Upvotes: 7

Related Questions