jQuery get Array of all <th> values

Viewed 45

I want to obtain an Array of all the inner texts of all <th>s in a table.

The following works

$("th").toArray().map(th => th.innerText)

Just wondering if there is a better way in straight jQuery (wo having to convert to Array and then use JS methods)

2 Answers

If you're looking to avoid creating an intermediate array with the .map, there's a more efficient method without jQuery, which only creates a single array for the output, but it requires more source code:

const texts = Array.from(
  document.querySelectorAll('th'),
  th => tx.innerText
);

From your original version, you can use jQuery's .text by mapping before the .toArray:

const texts = $("th").map(function() { return $(this).text(); }).toArray();
console.log(texts);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr><th>foo</th></tr>
</table>

But you probably want to use .textContent instead of .innerText instead.

jQuery has its own .map() method that will map over a collection. It returns a collection of the results, and you can use .get() to convert that to an array at the end.

$("th").map((i, el) => el.innerText).get();
Related