0

My goal is to create one array and later on insert some data using .unshift method.

I want an array to contain td elements only and be created using JavaScript instead of jQuery. Is it possible?

Here's my table :

<table id="scorestable">
    <tr>
        <th>Type</th>
        <th>Score</th>
        <th>Score</th>
        <th>Type</th>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    .....
Munawir
  • 3,346
  • 9
  • 33
  • 51
O. Barinov
  • 161
  • 1
  • 1
  • 12

2 Answers2

1

simply use:

var elements = document.getElementById("scorestable").getElementsByTagName('td');

then you will have: elements[0] , elements[1] and etc..

T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • 1
    That's not an array, so it won't have `unshift`. It will live-update, but we don't know that's what the OP wants. –  Sep 23 '16 at 21:10
  • Array like objects FTW! – evolutionxbox Sep 23 '16 at 21:10
  • See http://stackoverflow.com/questions/4557817/convert-nodelist-to-array?s=1|3.2666 for how to convert the `NodeList` to an array. – Barmar Sep 23 '16 at 21:50
  • As @adil.hilmi's answer shows, you only need to add `Array.prototype.slice.call();` to get an `Array` from a `NodeList` – jconder Sep 23 '16 at 21:55
0
<table id="scorestable">
  <tr>
    <th>Type</th>
    <th>Score</th>
    <th>Score</th>
    <th>Type</th>
  </tr>
  <tr>
    <td>33</td>
    <td></td>
    <td>6</td>
    <td></td>
  </tr>
</table>

<script>
  window.onload = function(e) {
    var arrayResult = [];
    var tdList = Array.prototype.slice.call(document.getElementById("scorestable").getElementsByTagName('td'));
    tdList.forEach(function logArrayElements(element, index, array) {
      if (element.innerText && element.innerText != "undefined") {
        arrayResult.unshift(element.innerText);
      }
    });
    console.log(arrayResult);
  }

</script>
adil.hilmi
  • 197
  • 5