0

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.

3
  • What is the HTML? Commented Oct 22, 2018 at 8:11
  • Added jsfiddle link Commented Oct 22, 2018 at 8:12
  • x is the index of the element. Use $(this).text(), and also don't forget to call get() after map() Commented Oct 22, 2018 at 8:16

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

2 Comments

still need to use .get() at the end.
thks for the torough and lightning-speed explanation - will validate the answer when I can
0

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

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.