6

Here is JSFiddle exapmle: https://jsfiddle.net/1a6j4es1/1/

$('table').on('click', 'td', function() {
    $(this).css('background', 'green');
});

How can this code be rewritten in plain JavaScript?
Callback function should work even for new td elements inside the table element.

Update: I found out a very short and clean solution: https://jsfiddle.net/1a6j4es1/28/

function delegateSelector(selector, event, childSelector, handler) {

    var is = function(el, selector) {
      return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector);
    };

    var elements = document.querySelectorAll(selector);
    [].forEach.call(elements, function(el, i){
        el.addEventListener(event, function(e) {
            if (is(e.target, childSelector)) {
                handler(e);                
            }
        });
    });
}

delegateSelector('table', "click", 'td', function(e) {
    e.target.style.backgroundColor = 'green';
});
0

2 Answers 2

1

Add an ID to the element you wish to click on, and use this code:

document.getElementById("tableId").addEventListener("click", function(e){
e.target.style.background = 'green';
});
10
  • 2
    what if there is a span or div inside a td?
    – charlietfl
    Commented Apr 6, 2015 at 16:36
  • @charlietfl what do you want to do with them?
    – Eyal
    Commented Apr 6, 2015 at 16:42
  • 1
    would want the parent <td> to change not the children. target might not be the `<td>
    – charlietfl
    Commented Apr 6, 2015 at 16:43
  • @charlietfl then instead of e.target, use document.getElementById("tableId") and you will get the specific element you want
    – Eyal
    Commented Apr 6, 2015 at 17:08
  • that would change the whole table not a single td. What is needed is to walk up the dom from target and test for td. Current solution oversimplifies the situation
    – charlietfl
    Commented Apr 6, 2015 at 17:09
0
<table id="clickable" onclick="changecolor(this)" border=1>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
</table>
<script>
    function changecolor(table)
    {
     document.getElementById("clickable").addEventListener("click",tableClicked);
      function tableClicked(e) {
       e.target.style.backgroundColor = 'green';
     }
    }
</script>

This worked for me ..

2
  • Doesn't work when one of the cells contains child elements. Or when there are <tr> cells.
    – Bergi
    Commented Apr 6, 2015 at 16:55
  • 1
    I fixed the solution: jsfiddle.net/1a6j4es1/27
    – Dmitry
    Commented Apr 7, 2015 at 2:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.