Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  157] [ 1]  / answers: 1 / hits: 25846  / 10 Years ago, mon, march 31, 2014, 12:00:00

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?


More From » html

 Answers
3

The following will only select the first element with class='cell'.


document.querySelector('.cell');

For adding event listener to all such elements, use querySelectorAll(),
which will return a NodeList (a kind of array of inactive DOM elements) having class='cell'. You need to iterate over it or access specific element using it's index.


For example:


var cells = document.querySelectorAll('.cell');
cells.forEach(cell => cell.addEventListener('mouseover', callback, false));

Check this fiddle


[#71696] Friday, March 28, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
erick

Total Points: 588
Total Questions: 92
Total Answers: 100

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
;