smuhero smuhero -4 years ago 74
HTML Question

How to loop through a string that contain multiple td using javascript?

Background story, I am working on a chrome extension that would allow people retrieve specific data from the user content page and do some calculation.

The problem I am having is how can I filter through a string that contain multiple td element, to get it's innerText and then store each one found into an array.

HTML Table content & Javascript:

<table id="countryList">
<tr>
<td>Europe</td>
<td>France</td>
<td>Sweden</td>
<td>Germany</td>
</tr>
<tr>
<td>Asia</td>
<td>Singapore</td>
<td>Thailand</td>
<td>Japan</td>
</tr>
</table>

var table = document.getElementById('countryList');
var tdArray = new Array;
for (var r = 0, n = table.rows.length; r < n; r++)
{
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
var stringContainTd = table.rows[r].cells[0].innerHTML);
}
}

//loop through stringContainTd to find each td element and store it's innerText into tdArray.

Answer Source

You can use querySelectorAll which will return list of matched element in an array. Then use forEach to loop through this array and use textContent to get the text

var arr = [];
var getTDContent = document.querySelectorAll('td');
getTDContent.forEach(function(item) {
  arr.push(item.textContent); // for pushing into arr
})
<table id="countryList">
  <tr>
    <td>Europe</td>
    <td>France</td>
    <td>Sweden</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Asia</td>
    <td>Singapore</td>
    <td>Thailand</td>
    <td>Japan</td>
  </tr>
</table>

Alternatively you can also use array.map method bu the catch is map does not work on nodelist, but Array.prototype.map.call will help in using map method

var arr = [],
  getTDContent = document.querySelectorAll('td');
arr = Array.prototype.map.call(getTDContent, function(item) {
  return item.textContent;
})
console.log(arr)
<table id="countryList">
  <tr>
    <td>Europe</td>
    <td>France</td>
    <td>Sweden</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Asia</td>
    <td>Singapore</td>
    <td>Thailand</td>
    <td>Japan</td>
  </tr>
</table>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download