Spygol Spygol - 23 days ago 6
Javascript Question

Set onclick for childnodes jquery or javascript

Hello I want to set a onclick for every table row in jquery, but i have no idea where to begin and I suck at searching so I was hoping to get some help here.
I've tried this

var tableRows = $("tableID").children();
console.log(tableRows);


But the console.log(tableRows) only returns Prev object r.fn.init[0], so I guess I don't have anything to work with from that. How can i get the tableRows in an array and run through them with a for loop?

Answer

Try this:

$('document').ready(function() {
  var tableRows = $("#tableID td");
  tableRows.on('click', function(e) {
    console.log('%s %s %s', e.target.tagName, e.target.innerHTML, "clicked");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tableID">
  <tr>
    <td>Row1</td>
  </tr>
  <tr>
    <td>Row2</td>
  </tr>
</table>