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>
    .....
2
  • Is it possible? That's your question? Commented Sep 23, 2016 at 21:08
  • No, because you haven't tried anything. Commented Sep 23, 2016 at 21:10

2 Answers 2

1

simply use:

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

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

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

4 Comments

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.
Array like objects FTW!
See stackoverflow.com/questions/4557817/… for how to convert the NodeList to an array.
As @adil.hilmi's answer shows, you only need to add Array.prototype.slice.call(<SomeNodeList>); to get an Array from a NodeList
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>

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.