简体   繁体   中英

How to change background color of a specific 'td' element having no id/class, when it is clicked?

I am working on a large table (say 100*100) in HTML. So, unable to provide every element its id/class. And I want to change the bg color of the cell which is clicked (by means of javascript). How would I know which cell is clicked or please suggest me any other alternative to do the same.

You could set an handler on the table and capture the click event via event delegation during the bubbling phase . This will avoid to set an handler on each cell of the table, which can be really expensive especially when the table has a lot of cells (as in your specific scenario).

Javascript

let table = document.querySelector('table'); 
/* or other selector retrieving the table */

table.addEventListener('click', function(ev) {
   let tgt = ev.target.nodeName.toLowerCase();
   if (tgt === 'td') {
      tgt.classList.add('selected');
   }
});

With this script a .selected class will be applied once to the cell that received the click event. The choice to use a classname instead of setting an inline style allow you to keep off the style from the javascript, so your code can be more mantainable.

CSS

.selected {
   background: yellowgreen;
}

You can use this to get the clicked element inside the click callback, and then use .css to change its background color.

 $("td").click(function(){ $(this).css("background-color", "#ff0000"); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table border=1> <tr> <td>Col 1</td> <td>Col 2</td> </tr> </table> 

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $("td").click(function(){
        $(this).css("background-color", "#ff0000");
        $(this).siblings().css("background-color", "transparent");
    })
});
</script>
</head>
<body>

<table border=1>
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
    <td>Col 4</td>
    <td>Col 5</td>
  </tr>
</table>

</body>
</html>

 $(document).ready(function(){ $("td").click(function(){ $(this).closest("table").find("td").css("background-color", "transparent"); $(this).css("background-color", "#ff0000"); }) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table border=1> <tr> <td>Col 1</td> <td>Col 2</td> <td>Col 3</td> <td>Col 4</td> <td>Col 5</td> </tr> <tr> <td>Col 1</td> <td>Col 2</td> <td>Col 3</td> <td>Col 4</td> <td>Col 5</td> </tr><tr> <td>Col 1</td> <td>Col 2</td> <td>Col 3</td> <td>Col 4</td> <td>Col 5</td> </tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM