Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jlrdw's avatar
Level 75

Jquery td to Javascript td

I have this in jquery all works:

    $(document).ready(function () {

        $("#checktable td:nth-child(1)").click(function (event)  //  This line I need converted
        {
            event.preventDefault();
            
            var $td = $(this).closest('tr').children('td');  //This line I need converted
            var tid = $td.eq(0).text();
            var tdate = $td.eq(1).text();
            var tdescribe = $td.eq(2).text();
            var wd = $td.eq(3).text();
            var dep = $td.eq(4).text();

            // more code
           

I need a similar thing in javascript, above only first td is clicked.

My javascript code so far:

    function addRowHandlers() {
        var table = document.getElementById("checktable2");
        var rows = table.getElementsByTagName('tr');
        var tid = '';
        var tdate = '';
        var tdescribe = '';
        var wd = '';
        var dep = '';
        var tisclr = '';

        for (var i = 1; i < rows.length; i++) {

            rows[i].i = i;
            rows[i].onclick = function () {
                tid = table.rows[this.i].cells[0].innerText;
                tdate = table.rows[this.i].cells[1].innerHTML;
                tdescribe = table.rows[this.i].cells[2].innerHTML;
                wd = table.rows[this.i].cells[3].innerHTML;
                dep = table.rows[this.i].cells[4].innerHTML;

               // etc more code

The javascript works but any td can be clicked, I am after only:

  • First td clicked
  • Then get parent row
  • Then all child td's

I have been over dozens of stackoverflow post and other sites as well... Thanks

And how do I add the event.preventDefault(); to regular JS in such a case.

0 likes
4 replies
jlrdw's avatar
Level 75

@tray2 Just an old app I'm converting so when you get back please post the code. Thanks.

And thanks for your tip on fetch on the other post it's working out pretty good.

2 likes
mabdullahsari's avatar

The thing is, you have to decide whether you want to make use of event delegation or not. In your first example, there is no event delegation even if it looks like it because jQuery does a "foreach" behind the scenes on the selector you have provided.

In your conversion attempt, you are trying to make use of event delegation but it won't be straight forward without a few data attributes to determine the selection of the correct element.

1 like

Please or to participate in this conversation.