Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 969
vladys.bo Avatar asked Mar 31 '14 16:03

vladys.bo


2 Answers

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

like image 156
T J Avatar answered Oct 04 '22 22:10

T J


I would rather use event delegation for this.

document.getElementById('your-table').addEventListener('mouseover', function (e) {
    var t = e.target;

    if (t.classList.contains('cell')) {
        console.log(t.textContent);
    }
});

However "It doesen't work, or maybe I did mistakes?"

  • querySelector returns a single element.
  • cell.addEventListener('mouseover',callback(), here callback() calls the callback function right away and that's not what you want. You want to pass the function reference so remove the ().

Note that even if you use querySelectorAll which returns a node list, it doesn't implement the Composite pattern so you cannot treat a list as a single element like you would do with a jQuery object.

like image 27
plalx Avatar answered Oct 04 '22 22:10

plalx