How to put the contents of all elements in an array using jQuery?
jQuery provides .map()for this:
var items = $('#main p').map(function () { return $(this).text(); }).get();
.map() iterates over its elements, calling a function for each of them and writing the return value of the function to a new array that it returns.
You could also solve this with a simple .each():
var items = [];
$('#main p').each(function (i, e) {
items.push($(e).text());
});
This will work:
var p = $('#main p').map(function () {
return '"' + $(this).text() + '"';
}).get().join(',');
p = "[" + p + "]";
map () allows you to iterate over each match and get a value from it that is inserted into an object that looks like an array. get () then returns it as a Javascript array, and .join turns the array into a string.