3

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?

2 Answers 2

7

Use .map():

var arr = $('.class1 p').map(function () {
    return $(this).text();
}).get();
Sign up to request clarification or add additional context in comments.

2 Comments

@Bjarki, without the .get(), the array is jQuery-wrapped, which still works, but you have meaningless functions like find, click, etc, still attached.
More specifically, .map() returns a jQuery object and .get() creates a native array from its elements.
2

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();
});

1 Comment

Box9's solution is more idiomatic jQuery (and probably better), though both are valid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.