user3734782
user3734782

Reputation: 137

Select table cell using class in javascript

Is there a way I can select table cell by using 'class' used on the cell. Well example is better than 1000 words...

How can I select elements using javascript to select .redcell only in the table? I need to insert function for every td separately, so td .redcell is not a solution as well as the indexes.

.redcell {background-color: red}
<table>
    <tr>
      <td> 1</td>
      <td>2</td>
      <td class="redcell">3</td>
      <td>4</td>
  </tr>
      <tr>
      <td> 1</td>
      <td class="redcell">2</td>
      <td>3</td>
      <td>4</td>
  </tr>
</table>
<div class="redcell">don't select me</div>

Upvotes: 0

Views: 7053

Answers (3)

koninos
koninos

Reputation: 5357

In jQuery, you can use the following selector to select only td elements with the redcell class:

$("td.redcell")

Its equivalent in pure JS:

document.querySelectorAll('td.redcell');

Upvotes: 0

Saad
Saad

Reputation: 952

Instead of iterating through each elements that contains redcell class, you should use delegation. In that case, you don't need to add another event listener for dynamically added <td> and also, the code looks cleaner.

Add click event listener to one of the ancestor element of <td>. Here, the ancestor element can be <table>. When you click a <td>, the click event handler will get called. Find the clicked element information by event.target and if event.target is <td> and has redcell class,then perform your logic.

See this demo.

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122087

You could use querySelectorAll() DEMO

var cell = document.querySelectorAll('table td.redcell');
for (var i = 0; i < cell.length; i++) {
  cell[i].style.color = 'red';
}

Update: You can addEventListener to each cell like this

var cell = document.querySelectorAll('table td.redcell');
cell[0].addEventListener('click', function() {
  this.style.color = 'red';
});

cell[1].addEventListener('click', function() {
  this.style.color = 'green';
})
<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td class="redcell">3</td>
    <td>4</td>
  </tr>
  <tr>
    <td>1</td>
    <td class="redcell">2</td>
    <td>3</td>
    <td>4</td>
  </tr>
</table>
<div class="redcell">don't select me</div>

Upvotes: 2

Related Questions