vladja vladja - 5 months ago 9
HTML Question

Add event listener to DOM elements based on class

I have a table, where each

tr
and
td
have only classes, I have a problem with selection of
td
element having the class I need

HTML:

<table>
<tr class="data">
<td class="cell">1</td>
<td class="cell2"></td>
</tr>
<tr class="data">
<td class="cell">2</td>
<td class="cell2"></td>
</tr>
</table>


When mouseover
td
with
class="cell"
I have to get text between
td
on which my mouse and do something with this. This should be done with pure JavaScript, without frameworks. I tried:

var cell = document.querySelector('.cell');

function callback(){ //do something }
cell.addEventListener('mouseover',callback(),false);


It doesn't work, or maybe I did mistakes?

T J T J
Answer
document.querySelector('.cell');

Will only select the first element having class='cell'.

For adding event listener to all such elements, use querySelectorAll()

which will return a NodeList (sort of an array of inactive dom elemants) having class='cell'. You need to iterate over it or access one element using index.

For exapmle something like

var cell =document.querySelectorAll('.cell');
for(var i=0;i<cell.length;i++){
  cell[i].addEventListener('mouseover',callback,false);
}

check this fiddle

Comments