How to add onclick Event to Table Cells using JavaScript

← PrevNext →

There are two simple ways you can add an onclick event to Table cells dynamically using JavaScript. You can either use the setAttribute() method to assign or add an onclick event explicitly to a table cell, or you can use the addEventListner() method to capture click events on table cells.

Let us assume, I am creating an HTML table dynamically using JavaScript. Now, I have to add onclick (or click) event to cells in every row of a particular column. You can however add click event to every cell, if you want.

1) Using “setAttribute()” Method

In the first example, I’ll be using the setAttribute() method to attach or add an onclick event to cells of a particular column.

The setAttribute() method in JavaScript is often used to add attributes (like onclick, onblur, assign ids etc.) to elements dynamically.

<body>
  <input type='button' onclick='tableFromJson()' id='bt' value='Create a Table' />
  <p id='showData'></p>
</body>

<script>
  let tableFromJson = () => {
    // the json data.
    const birds = [
        {"ID": "001", "Bird": "Eurasian Collared-Dove"},
        {"ID": "002", "Bird": "Bald Eagle"},
        {"ID": "003", "Bird": "Cooper's Hawk"},
    ];

    let col = [];
    for (let i = 0; i < birds.length; i++) {
      for (let key in birds[i]) {
        if (col.indexOf(key) === -1) {
          col.push(key);
        }
      }
    }

    const table = document.createElement("table");
    let tr = table.insertRow(-1);               // table row.

    for (let i = 0; i < col.length; i++) {
      let th = document.createElement("th");      // table header.
      th.innerHTML = col[i];
      tr.appendChild(th);
    }

    for (let i = 0; i < birds.length; i++) {
      tr = table.insertRow(-1);

      for (let j = 0; j < col.length; j++) {
        let tabCell = tr.insertCell(-1);
        tabCell.innerHTML = birds[i][col[j]];
        if (col[j] === 'Bird') {
          tabCell.setAttribute('id', 'br_' + birds[i][col[j]]);
          tabCell.setAttribute('onclick', 'alert(this.innerHTML)');     // Attach the onclick event.
        }
      }
    }

    // Add table.
    const div = document.getElementById('showData');
    div.innerHTML = "";
    div.appendChild(table);
  }
</script>
</html>
Try it

Look carefully, I have used the setAttribute() method twice in the above example. Its when I am running a loop to insert values in the table cells, I am assigning a unique id to each cell of the 2nd column (Bird) and simultaneously attaching the onclick event to the cells, using the method.

if (col[j] === 'Bird') {
    tabCell.setAttribute('id', 'br_' + birds[i][col[j]]);
    tabCell.setAttribute('onclick', 'alert(this.innerHTML)');
}

Since I want to attach the onclick event to cells of a particular column, I have set a condition checking the column value.

2) Using “addEventListner()” Method

This is another method you can capture click events of a particular element. Now, with this I am not adding or attaching the event explicitly to an element (or the table cells). However, this method can also be used in some cases.

<script>
  if (window.addEventListener) {
    document.addEventListener('click', function (e) {
      if (e.target.id.indexOf('br') === 0) {
        alert(e.target.innerHTML);
      }
    });
  }

  let tableFromJson = () => {
    // the json data.
    const birds = [
        {"ID": "001", "Bird": "Eurasian Collared-Dove"},
        {"ID": "002", "Bird": "Bald Eagle"},
        {"ID": "003", "Bird": "Cooper's Hawk"},
    ];

    let col = [];
    for (let i = 0; i < birds.length; i++) {
      for (let key in birds[i]) {
        if (col.indexOf(key) === -1) {
          col.push(key);
        }
      }
    }

    const table = document.createElement("table");
    let tr = table.insertRow(-1);               // table row.

    for (let i = 0; i < col.length; i++) {
      let th = document.createElement("th");      // table header.
      th.innerHTML = col[i];
      tr.appendChild(th);
    }

    for (let i = 0; i < birds.length; i++) {
      tr = table.insertRow(-1);

      for (let j = 0; j < col.length; j++) {
        let tabCell = tr.insertCell(-1);
        tabCell.innerHTML = birds[i][col[j]];
        if (col[j] === 'Bird') {
          tabCell.setAttribute('id', 'br_' + birds[i][col[j]]);
        }
      }
    }

    // Add table.
    const div = document.getElementById('showData');
    div.innerHTML = "";
    div.appendChild(table);
  }
</script>
Try it

Now, here I am not explicitly adding an onclick event to a cell using any method. However, I am using the setAttribute() method to assign a unique id to every cell in the 2nd column.

This piece of code is important in the above example.

 if (window.addEventListener) {
    document.addEventListener('click', function (e) {
      if (e.target.id.indexOf('br') === 0) {
        alert(e.target.innerHTML);
      }
    });
  }

The listener captures the click event, and it checks the id (that I have assigned to the cells) and accordingly shows the value.

Similarly, you can assign ids to every cell of a column and capture the values on click event.

← PreviousNext →