-1

JavaScript does not detect clicks on table cells, code does not work. Code:

document.querySelectorAll("td").forEach(e => e.addEventListener("click", function(){
    console.log(this.cellIndex);
    console.log(this.innerText);
    console.log(document.querySelectorAll("th")[this.cellIndex].innerText);
}));

If I paste this code into the console it works, but as a separate .js file or in html code it does not work. What could be wrong?

norbitrial
  • 12,734
  • 5
  • 20
  • 46
BartTed
  • 5
  • 4
  • Can you please share how you link the JavaScript file in your HTML? Maybe there is any issue in that piece. Thanks! – norbitrial Feb 23 '20 at 14:32
  • in the head section of the html file I have: When I add beyond the proper function e.g. console.log it works – BartTed Feb 23 '20 at 14:35
  • Probably duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Heretic Monkey Feb 23 '20 at 15:00

1 Answers1

0

If you are linking the above code as a separate JS files, and your importing script tags are in <head>, make sure that all DOM related functions must be in DOMContentLoaded or load event callback.

For this instance, change your script in your external js file into:

onload = () => {

    document.querySelectorAll("td").forEach(e => e.addEventListener("click", function(){
        console.log(this.cellIndex);
        console.log(this.innerText);
        console.log(document.querySelectorAll("th")[this.cellIndex].innerText);
    }));

}

edit 1:

After knowing that it is after Ajax,

First of all, querySelectorAll returns a NodeList, and it doesn't have forEach method.

Use Array.from(document.querySelectorAll()).forEach instead.

Secondly, put the code in the callback of AJAX create td callback.

Gordon
  • 51
  • 3
  • This works but only for the table that was on the web page in the source code. I need a solution that will works with tables inserted by ajax. – BartTed Feb 23 '20 at 14:49
  • I see, I don't see mentioning ajax in the original question. Let me edit my answer. – Gordon Feb 23 '20 at 14:53
  • Thanks, it works. I put addEventListener in a function and then I added a call to it in ajax script. – BartTed Feb 23 '20 at 15:01