Chapo
Chapo

Reputation: 2543

.map() function on Jquery array confusion

I am trying to achieve something very simple but can't quite get it to work properly.

I am looping through the td children of a tr and trying to get the values of the cell into an array.

$($("#thetable").find("tr")[0]).find("td").map(function(x) {return $(x).innerText;});

What am I doing wrong ?

jsFiddle if that helps.

Upvotes: 0

Views: 76

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370759

As usual, with jQuery array-like methods, the first argument is the index, not the element in question. Another problem is that innerText is a property of a plain element, not a jQuery collection - either use the jQuery version (.text()), or don't convert the element to a jQuery collection first:

var rows = $("#thetable").find("tr")
var test = $(rows[0]).find("td").map(function(_, x) { return x.innerText;});
console.log(test);
  <table id="thetable">
  <tr>
    <td>20</td>
    <td>2</td>
    <td>10</td>
    <td>30</td>
    <td>50</td>
  </tr>
  </table>
</div>

Of course, using .map on a jQuery collection will give you a jQuery collection in return - if you don't want that, either call .get() on the result to convert it to an array

var test = $(rows[0]).find("td").map(function(_, x) { return x.innerText;}).get();

or simply use a native array method in the first place, rather than jQuery (there's no need for jQuery for something this simple anyway):

const arr = Array.prototype.map.call(
  document.querySelectorAll('#thetable td'),
  td => td.textContent
);
console.log(arr);
<div id="banner-message">
  <table id="thetable">
  <tr>
    <td>20</td>
    <td>2</td>
    <td>10</td>
    <td>30</td>
    <td>50</td>
  </tr>
  </table>
</div>

Upvotes: 3

madalinivascu
madalinivascu

Reputation: 32354

The x value stores the index of the element found not the element, use this to get the current element and text() to get the inner text:

var rows = $("#thetable").find("tr")
console.log($(rows[0]).find("td"));
var test = $(rows[0]).find("td").map(function(x) {return $(this).text();});
console.log(test);

demo

To transfrom the jquery object in a plain array use the get() method

console.log(test.get());

Upvotes: 0

Related Questions