Text1

Text2

Text3 The result sh...">

How to put the contents of all elements in an array using jQuery?

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

The result should be:

["text1","text2","text3"]
+3
source share
2 answers

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

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.

0
source

Source: https://habr.com/ru/post/1791033/


All Articles