Table styling (v5)

Revision 5 of this benchmark created on


Description

https://learn.javascript.ru/dom-navigation

Preparation HTML

<table>
  <tr>
    <td>1:1</td>
    <td>2:1</td>
    <td>3:1</td>
    <td>4:1</td>
    <td>5:1</td>
  </tr>
  <tr>
    <td>1:2</td>
    <td>2:2</td>
    <td>3:2</td>
    <td>4:2</td>
    <td>5:2</td>
  </tr>
  <tr>
    <td>1:3</td>
    <td>2:3</td>
    <td>3:3</td>
    <td>4:3</td>
    <td>5:3</td>
  </tr>
  <tr>
    <td>1:4</td>
    <td>2:4</td>
    <td>3:4</td>
    <td>4:4</td>
    <td>5:4</td>
  </tr>
  <tr>
    <td>1:5</td>
    <td>2:5</td>
    <td>3:5</td>
    <td>4:5</td>
    <td>5:5</td>
  </tr>
</table>

Test runner

Ready to run.

Testing in
TestOps/sec
Solution from tutorial — native table collections
function paintDiagonal() {
	const table = document.body.firstElementChild;

	for (let i = 0; i < table.rows.length; i++) {
		let row = table.rows[i];
		row.cells[i].style.backgroundColor = 'red';
	}

}

document.addEventListener("DOMContentLoaded", paintDiagonal);
ready
My naive solution with two for...of cycles
function paintDiagonal() {
	const tableRows = document.body.firstElementChild.rows;
	for (let tr of tableRows) {
		let currentRowCellIndex = 0;
		for (let td of tr.children) {
			if (currentRowCellIndex === tr.rowIndex) {
				td.style.backgroundColor = 'red'; 
			}
			currentRowCellIndex++
		}
		currentRowCellIndex = 0;
	}
}


document.addEventListener("DOMContentLoaded", paintDiagonal);
ready
Not using native table collections at all
function paintDiagonal() {
	const tableRows = document.body.firstElementChild.firstElementChild.children;
    let currentRowIndex = 0;
	for (let tr of tableRows) {
		let currentRowCellIndex = 0;
		for (let td of tr.children) {
			if (currentRowCellIndex === currentRowIndex) {
				td.style.backgroundColor = 'red';
			}
			currentRowCellIndex++
		}
		currentRowCellIndex = 0;
		currentRowIndex++;
	}
}


document.addEventListener("DOMContentLoaded", paintDiagonal);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.