4
<div id="main">
<p>Text1</p>
<p>Text2</p>
<p>Text3</p>
</di>

Result should be :

["text1","text2","text3"]

2 Answers 2

18

jQuery provides .map() for this:

var items = $('#main p').map(function () { return $(this).text(); }).get();

.map() iterates over its elements, invoking a function on each of them and recording the return value of the function in a new array, which it returns.

You could also have solved this with a simple .each():

var items = [];

$('#main p').each(function (i, e) {
  items.push($(e).text());
});
Sign up to request clarification or add additional context in comments.

1 Comment

Is not there a more concise way
0

This will work:

var p = $('#main p').map(function () {
        return '"' + $(this).text() + '"';
    }).get().join(',');
    p = "[" + p + "]";

map() lets you iterate over each match and get a value from it, which is inserted into an array-like object. get() then returns it as a Javascript array, and .join makes the array into a string.

Comments

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.