How to create an array of html content?

Here is the HTML:

<table>
  <tbody>
    <tr>
      <td>1</td>
      <td>one</td>
    </tr>
    <tr>
      <td>2</td>
      <td>two</td>
    </tr>
  </tbody>
</table>

Now I need to make an array of the second column of this table as follows:

var arr = ['one', 'two'];

How can i do this?

I can select a table like this $('table')and get its contents as follows: $('table td+td')but I don’t know how I can create an array from them.

+4
source share
2 answers

You can use :nth-child()to select the second tdand map()to return a DEMO array

var arr = $('table td:nth-child(2)').map(function() {
  return $(this).text();
}).get();
+2
source

Try the following:

Use $("table td:nth-child(2)").each()to cycle through the entire 2nd td and get its text with.text()

var arr = new Array();
$("table td:nth-child(2)").each(function(i){
  arr[i] = $(this).text();
})
+1
source

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


All Articles