How to Access element from Table using JavaScript?


To access a <tr> element from a table using JavaScript, you can first use the document.getElementById() or document.getElementsByTagName() method to access the table element. Then, you can use the table's childNodes property to access the <tr> elements within the table.

Our focus will be on changing the background color of the current row (the row on which we currently are) when we hover over it and reverting the background color to normal when the mouse goes away.

Example

Therefore, let’s suppose we have the following HTML code to render a table.

<!DOCTYPE html>
<html>
<head>
   <title>
   	Access tr element
   </title>
   <style type="text/css">
   	th,
   	td {
   		padding: 8px;
   		text-align: left;
   		border-bottom: 1px solid #ccc;
   	}
   </style>
</head>
<body>
   <table id="my_table">
      <tr>
         <th>Player</th>
         <th>Country</th>
         <th>Role</th>
      </tr>
      <tr>
   	   <td>Virat Kohli</td>
   	   <td>India</td>
   	   <td>Middle Order Batsman</td>
      </tr>
     	<tr>
         <td>Steve Smith</td>
         <td>Australia</td>
         <td>Middle Order Batsman</td>
      </tr>
      <tr>
         <td>Jofra Archer</td>
         <td>England</td>
         <td>Opening Fast Bowler</td>
      </tr>
      <tr>
         <td>Rashid Khan</td>
         <td>Afghanistan</td>
         <td>Spin All-Rounder</td>
      </tr>
   </table>
</body>
</html>

This is how the table looks like in the beginning −

Our task is to add a darker background to the row we hover upon and remove that background once the mouse goes away from the row.

Approach

  • Since we need to handle and apply particular styling to <tr> (table row), instead of the whole table, we will try to somehow select the rows of the table.

  • We will use the document.getElementByTagName function to select all <tr> (table rows).

  • Then while looping over the rows, we will attach event listeners to them listening for hover events.

  • And then at last inside the event listener we will write our logic of changing the color.

Example

Therefore, the final code will look something like this −

<!DOCTYPE html>
<html>
<head>
   <title>
   	Hello World
   </title>
   <style type="text/css">
   	th,
   	td {
   		padding: 8px;
   		text-align: left;
   		border-bottom: 1px solid #ddd;
   	}
   </style>
</head>
<body>
   <table id="my_table">
   	<tr>
   		<th>Player</th>
   		<th>Country</th>
   		<th>Role</th>
   	</tr>
   	<tr>
   		<td>Virat Kohli</td>
   		<td>India</td>
   		<td>Middle Order Batsman</td>
   	</tr>
   	<tr>
   		<td>Steve Smith</td>
   		<td>Australia</td>
   		<td>Middle Order Batsman</td>
   	</tr>
   	<tr>
   		<td>Jofra Archer</td>
   		<td>England</td>
   		<td>Opening Fast Bowler</td>
   	</tr>
   	<tr>
   		<td>Rashid Khan</td>
   		<td>Afghanistan</td>
   		<td>Spin All-Rounder</td>
   	</tr>
   </table>
	<script>
      const tableRows = document.getElementsByTagName('tr');
      // starting from 1 instead of 0
      // because we don’t want to apply the styling to header
      for (let curr = 1; curr < tableRows.length; curr++) {
         tableRows[curr].addEventListener('mouseover', function(e){
            console.log("over");
            tableRows[curr].style.backgroundColor = '#aaa';
         });
            tableRows[curr].addEventListener('mouseleave', function(e){
               console.log("leave");
               tableRows[curr].style.backgroundColor = '';
         });
      }
	</script>
</body>
</html>

Understanding the code

  • This HTML code creates a table with a header row and four data rows.

  • The table has basic styling to add padding and a border to the cells.

  • The JavaScript code adds event listeners to each data row that change the background color of the row when the mouse hovers over it and change it back to the default when the mouse leaves.

  • The console will also log "over" and "leave" when the mouse enters and leaves the row respectively.

Updated on: 06-Feb-2023

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements