1

I have created table cells in html that have ids that increment by 1 for example: cell1, cell2, cell3, ......, cell100.

What I would like to do is loop through and get reference to each of these cells using a for loop because referencing them one by one won't be good pratice and will require alot of codes of line, instead of this;

 var cell1 = document.getElementById('cell1');
 var cell2 = document.getElementById('cell2');
 var cell3 = document.getElementById('cell3');
 ......
 var cell100 = document.getElementById('cell100');

Is it possible to do something like this?

  for (i = 0; i<=100; i++) {
    var cell+i = document.getElementById("cell"+i);
    // then I can call individual cells and assign tasks to them something along the lines of;    
    cell1.addEventListener('input',function(){}
    cell5.background = '#f5f5f5'
    cell55.innerHTML = 'I am cell 55'
    etc..                     


   } 

EDITED:

Incase it might be useful, I have 1 table that contains many cells of which some have ids and some don't. I would only like to reference the ones that do have ids.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Henry
  • 1,042
  • 2
  • 17
  • 47

6 Answers6

1

you can use document.querySelectorAll with a wildcard

var slice = Array.prorotype.slice;
var selection = document.querySelectorAll("[id^=cell]");
slice.call(selection).forEach(function(item, index){
  // here item is the table row and index is the iteration number of forEach
  // to get the id
  var id = item.id;

  //to get the numerical value in id
  var number_in_id = item.id.match(/\d+/g)[0];
})

document.querySelectorAll("[id^=cell]") selectects all elements that their id starts with the string cell if you want to make it specific for table td's you add document.querySelectorAll("td[id^=cell]")

eltonkamami
  • 5,134
  • 1
  • 22
  • 30
  • Hi, sorry I am little confused by this code. Say for example, if I wanted to do something with cell that is referenced id 5, how would I do that? – Henry Feb 16 '16 at 13:20
  • @Henry in that case once the forEach loop reached to that element `var number_in_id = item.id.match(/\d+/g)[0];` would equal 5; so with a simple if statement `if(number_in_id === 5){ /* do your thing */ }`. id would also be `cell5` – eltonkamami Feb 16 '16 at 13:31
  • but how can I reference the cell 5, if I wanted to change the innerHTML of cell 5 how can I do that. Sorry if this a silly question. – Henry Feb 16 '16 at 13:33
  • @Henry inside the function you do the check `if(id == "cell5") { item.innerHTML = "newHTML"}` – eltonkamami Feb 16 '16 at 13:36
  • Thanks, sorry I was just little confused. Will try it now. – Henry Feb 16 '16 at 13:38
0

may be you are looking for this

var grid = document.getElementById("grid");//grid is the id of the table
for (var i = 1, row; row = grid.rows[i]; i++)
    row.cells[0].textContent = "";//content of the starts with row 1..2..3 and so one than cell[0] or cell[1] and so on.
pks
  • 169
  • 1
  • 9
  • Hi, thanks for the prompt answer say for example if in the same table I haven't given ids to some cells will using this method reference them as well because I only want to reference the cells I have given ids to. – Henry Feb 16 '16 at 12:44
  • yeah it do .. but we can traverse thru any desired cell by this, this is choice i would perfer AFA i understand your question. – pks Feb 16 '16 at 12:57
0

Yes, it is quite easy, see below.

var cells = [];
for (var i = 0; i <= 100; i++) {
  cells[i] = document.getElementById("cell"+i);
  // do stuff....
  if( cells[55] ) {
    cells[55].innerHTML = 'I am cell 55';
  }
}
Michael Hobbs
  • 1,663
  • 1
  • 15
  • 26
  • Hi, I am getting this error: Uncaught TypeError: Cannot set property 'innerHTML' of undefined – Henry Feb 16 '16 at 12:38
  • @Henry this might be because your cell55 doesn't actually have an `id` attribute, so previous line returns `undefined`, which cannot be set `innerHTML` on. You can try to patch it with `if(cells[i]) { .. do stuff }` inside the loop – robjez Feb 16 '16 at 12:43
  • please could you show me an example of this in your code? – Henry Feb 16 '16 at 13:11
  • Thanks I will try it now. – Henry Feb 16 '16 at 13:22
  • it seems to work now but would I need to do this for each cell I want to edit? e.g. write if statement for each cell I wish to do something with? – Henry Feb 16 '16 at 13:25
  • Yes, it sounds like you have a solution issue. It might be better to ask, "I need to do X and this is how I have approached it. How might I do it better?" – Michael Hobbs Feb 16 '16 at 13:27
0

It'd be good pratice to use classes, though;

In base of your loop, you can do it so to get the current element, but if you have an loop more longer than the amount of the elements id numbers sequence, then it will be returning errors.

var Cell=document.getElementById("cell"+i)
//you've your DOM element in the variable called Cell now
//the one error you did is in the variable name
//you used the + operator in the variable name;

That's equivalent to element with id "cell0" when it's the first execution time of the loop. Not too elegant, you've many other ways to do the same.

  • but I thought by using +i in the variable number it should create i amount of varaibles e.g. variable for cell1, cell2 etc – Henry Feb 16 '16 at 12:41
  • so does this assign variable to each id in the format of arrays? e.g. cell[0] would be id name cell1? – Henry Feb 16 '16 at 12:42
  • @Henry No. `var cell+i` is invalid, operators cannot be used in variables name, nor strings or another values type. THE ONE THING YOU CAN DO IS ASIGN AN OPTIONAL VALUE TYPE. –  Feb 16 '16 at 12:43
  • @Henry You can't use symbols in variables name, nor get/use path. var/property[number/property] is used only in arrays or objects to get or set property/item value, but not usable in declarament of variable and you can turn the variable an array too. –  Feb 16 '16 at 12:45
  • Why not just push the cells onto an array? `cellArray.push(document.getElementById("cell"+i));` – Hydrospanners Feb 16 '16 at 12:54
  • @Hydrospanners If he do so, then it'd be more simpler to use classes, not? Simply... `getElementsByClassName` or `querySelectorAll`, then you get an array with a lot of elements as items. –  Feb 16 '16 at 12:56
0

Consider you have a table with an ID as myTable.

Get the table with,, var theTable = document.getElementById('myTable');

To get all <td>s you could do,

var cells = theTable.querySelectorAll('td');

Then do the looping part,

for(var i = 0; i < cells.length; i++){
       if(cells[i].id && cells[i].id.indexOf('cell') != -1){ //added to get only the significant cells
               //do your stuff
              cells[i].addEventListener(function(){});
              cells[i].innerHTML = 'Something';
           }

}
Sudhansu Choudhary
  • 3,322
  • 3
  • 19
  • 30
  • but does this only take into account the cells that have an id or will it reference all the cells in the table? – Henry Feb 16 '16 at 13:12
0

I'm lazy and didn't want to hand code any table, so I made Demo 2:

  • A form that'll accept a number of rows and columns

  • Can create <tr> and append to a table (0 to 100 rows)

  • Can create <td> and append to a <tr>(0 to 100 columns)

  • Assigns a unique id to every <tr> and <td>

  • The id pattern allows a human reader to locate <tr>s and <td>s

  • Each id for the <td> are displayed in each cell.

  • There's also two arrays, one for the <tr>(rowX) and one for the <td>(colY). There's many powerful methods for Array and having those 2 arrays you could even make a two-dimensional array.


Concerning the OP's request specifically about an id for cells on a table (complete or partial), I am aware that you have a pre-made table, so I'll take the key lines that make it possible in Demo 2 to assign ids:

row.setAttribute('id', 'r' + r);// Each row will have a numbered id (ex. r0 is row 1)


col.setAttribute('id', 'r' + r + 'c' + c);// Each cell will have a numbered id representing it's location (ex. r3c0 is located on row 4 column 1)

Demo 1

This snippet is an adaptation of the code previously mentioned:

  function oddRows() {

  var rows = document.querySelectorAll('tr');
  // rows is a NodeList (an array-like object).

  // We can covert this NodeList into an Array.
  var rowArray = Array.prototype.slice.call(rows);

  //Either way, NodeList or Array should be iterated through a for loop (most common way to reiterate)
  for (var i = 0; i < rowArray.length; i++) {

    if (i % 2 === 1) {
      console.log(i);
      var odd = rowArray[i];
      odd.style.display = "none";

      //This filters and removes all odd numbered rows    
    }
  }
  return false;
}

function evenCols() {
  var cols = document.querySelectorAll('td');
  var colArray = Array.prototype.slice.call(cols);
  for (var j = 0; j < colArray.length; j++) {

    if (j % 2 === 0) {
      console.log(j);
      var even = colArray[j];
      even.style.backgroundColor = "red";

      //This filters even numbered <td> and colors the background red.    
    }
  }
  return false;
}
td {
  border: 2px inset #777;
}
button {
  margin: 20px 5px 10px;
}
<button id="btn1" onclick="oddRows();">Remove Odd Rows</button>
<button id="btn2" onclick="evenCols();">Mark Even Cols</button>

<table id="t1">
  <tr id="r0" class="row">
    <td id="r0c0" class="col">r0c0</td>
    <td id="r0c1" class="col">r0c1</td>
    <td id="r0c2" class="col">r0c2</td>
    <td id="r0c3" class="col">r0c3</td>
    <td id="r0c4" class="col">r0c4</td>
    <td id="r0c5" class="col">r0c5</td>
    <td id="r0c6" class="col">r0c6</td>
    <td id="r0c7" class="col">r0c7</td>
    <td id="r0c8" class="col">r0c8</td>
    <td id="r0c9" class="col">r0c9</td>
  </tr>
  <tr id="r1" class="row">
    <td id="r1c0" class="col">r1c0</td>
    <td id="r1c1" class="col">r1c1</td>
    <td id="r1c2" class="col">r1c2</td>
    <td id="r1c3" class="col">r1c3</td>
    <td id="r1c4" class="col">r1c4</td>
    <td id="r1c5" class="col">r1c5</td>
    <td id="r1c6" class="col">r1c6</td>
    <td id="r1c7" class="col">r1c7</td>
    <td id="r1c8" class="col">r1c8</td>
    <td id="r1c9" class="col">r1c9</td>
  </tr>
  <tr id="r2" class="row">
    <td id="r2c0" class="col">r2c0</td>
    <td id="r2c1" class="col">r2c1</td>
    <td id="r2c2" class="col">r2c2</td>
    <td id="r2c3" class="col">r2c3</td>
    <td id="r2c4" class="col">r2c4</td>
    <td id="r2c5" class="col">r2c5</td>
    <td id="r2c6" class="col">r2c6</td>
    <td id="r2c7" class="col">r2c7</td>
    <td id="r2c8" class="col">r2c8</td>
    <td id="r2c9" class="col">r2c9</td>
  </tr>
  <tr id="r3" class="row">
    <td id="r3c0" class="col">r3c0</td>
    <td id="r3c1" class="col">r3c1</td>
    <td id="r3c2" class="col">r3c2</td>
    <td id="r3c3" class="col">r3c3</td>
    <td id="r3c4" class="col">r3c4</td>
    <td id="r3c5" class="col">r3c5</td>
    <td id="r3c6" class="col">r3c6</td>
    <td id="r3c7" class="col">r3c7</td>
    <td id="r3c8" class="col">r3c8</td>
    <td id="r3c9" class="col">r3c9</td>
  </tr>
  <tr id="r4" class="row">
    <td id="r4c0" class="col">r4c0</td>
    <td id="r4c1" class="col">r4c1</td>
    <td id="r4c2" class="col">r4c2</td>
    <td id="r4c3" class="col">r4c3</td>
    <td id="r4c4" class="col">r4c4</td>
    <td id="r4c5" class="col">r4c5</td>
    <td id="r4c6" class="col">r4c6</td>
    <td id="r4c7" class="col">r4c7</td>
    <td id="r4c8" class="col">r4c8</td>
    <td id="r4c9" class="col">r4c9</td>
  </tr>
  <tr id="r5" class="row">
    <td id="r5c0" class="col">r5c0</td>
    <td id="r5c1" class="col">r5c1</td>
    <td id="r5c2" class="col">r5c2</td>
    <td id="r5c3" class="col">r5c3</td>
    <td id="r5c4" class="col">r5c4</td>
    <td id="r5c5" class="col">r5c5</td>
    <td id="r5c6" class="col">r5c6</td>
    <td id="r5c7" class="col">r5c7</td>
    <td id="r5c8" class="col">r5c8</td>
    <td id="r5c9" class="col">r5c9</td>
  </tr>
  <tr id="r6" class="row">
    <td id="r6c0" class="col">r6c0</td>
    <td id="r6c1" class="col">r6c1</td>
    <td id="r6c2" class="col">r6c2</td>
    <td id="r6c3" class="col">r6c3</td>
    <td id="r6c4" class="col">r6c4</td>
    <td id="r6c5" class="col">r6c5</td>
    <td id="r6c6" class="col">r6c6</td>
    <td id="r6c7" class="col">r6c7</td>
    <td id="r6c8" class="col">r6c8</td>
    <td id="r6c9" class="col">r6c9</td>
  </tr>
  <tr id="r7" class="row">
    <td id="r7c0" class="col">r7c0</td>
    <td id="r7c1" class="col">r7c1</td>
    <td id="r7c2" class="col">r7c2</td>
    <td id="r7c3" class="col">r7c3</td>
    <td id="r7c4" class="col">r7c4</td>
    <td id="r7c5" class="col">r7c5</td>
    <td id="r7c6" class="col">r7c6</td>
    <td id="r7c7" class="col">r7c7</td>
    <td id="r7c8" class="col">r7c8</td>
    <td id="r7c9" class="col">r7c9</td>
  </tr>
  <tr id="r8" class="row">
    <td id="r8c0" class="col">r8c0</td>
    <td id="r8c1" class="col">r8c1</td>
    <td id="r8c2" class="col">r8c2</td>
    <td id="r8c3" class="col">r8c3</td>
    <td id="r8c4" class="col">r8c4</td>
    <td id="r8c5" class="col">r8c5</td>
    <td id="r8c6" class="col">r8c6</td>
    <td id="r8c7" class="col">r8c7</td>
    <td id="r8c8" class="col">r8c8</td>
    <td id="r8c9" class="col">r8c9</td>
  </tr>
  <tr id="r9" class="row">
    <td id="r9c0" class="col">r9c0</td>
    <td id="r9c1" class="col">r9c1</td>
    <td id="r9c2" class="col">r9c2</td>
    <td id="r9c3" class="col">r9c3</td>
    <td id="r9c4" class="col">r9c4</td>
    <td id="r9c5" class="col">r9c5</td>
    <td id="r9c6" class="col">r9c6</td>
    <td id="r9c7" class="col">r9c7</td>
    <td id="r9c8" class="col">r9c8</td>
    <td id="r9c9" class="col">r9c9</td>
  </tr>
</table>

If ids seem too heavy and cumbersome, you can select any cell on a table by using the pseudo-selectors nth-child and nth-of-type.

Example:

  • Target:* You want the 3rd <td> on the 5th row to have red text.

  • CSS:

     table tbody tr:nth-of-type(5) td:nth-of-type(3) { color: red; }
    
  • jQuery:

    $("table tbody tr:nth-of-type(5) td:nth-of-type(3)").css('color', 'red');
    
  • JavaScript:

    var tgt = document.querySelector("table tbody tr:nth-of-type(5) td:nth-of-type(3)");
    tgt.style.color = "red";
    

*Assuming that the target element has a table with a <tbody>


Demo 2

fieldset {
  width: 50vw;
  height: 55px;
  margin: 10px auto;
  padding: 3px;
}
input {
  width: 40px;
  height: 20px;
  margin: 5px 10px;
}
table {
  table-layout: fixed;
  border-collapse: collapse;
  border: 3px ridge #666;
  width: 50vw;
  height: 50vh;
  margin: 20px auto;
}
td {
  height: 20px;
  width: 20px;
  border: 1px inset grey;
  font-size: 8px;
}
<fieldset>
  <legend>Rows &amp; Columns</legend>
  <input id="rows" type="number" min="0" max="100" />
  <input id="cols" type="number" min="0" max="100" />
  <button id="btn1">Build</button>
</fieldset>

<table id="t1"></table>
<script>
  var t1 = document.getElementById('t1');
var rows = document.getElementById('rows');
var cols = document.getElementById('cols');
var btn1 = document.getElementById('btn1');

btn1.addEventListener('click', function(e) {
      var R = rows.value;
      var C = cols.value;
      var rowX = [];
      var colY = [];

      for (var r = 0; r < R; r++) {
        var row = document.createElement('tr');
        row.setAttribute('id', 'r' + r);// Each row will have a numbered id (ex. r0 is row 1)
        row.classList.add('row');
        rowX.push(row);
        t1.appendChild(row)
        for (var c = 0; c < C; c++) {
          var col = document.createElement('td');
          col.setAttribute('id', 'r' + r + 'c' + c);// Each cell will have a numbered id representing it's location (ex. r3c0 is located on row 4 column 1)
          col.innerHTML = col.id;
          col.classList.add('col');
          colY.push(col);
          row.appendChild(col);
        }
      }
    }, false);
</script>
Community
  • 1
  • 1
zer00ne
  • 41,936
  • 6
  • 41
  • 68