I am getting a cloneNode error Uncaught TypeError: Cannot read property 'cloneNode' of null at application.js:42
when I move my script into a javascript file. But the application works when the script is in the HTML page.
const candidatesTable = document.getElementById("candidates_example");
const newCandidatesTable = candidatesTable.cloneNode(true);
document.body.appendChild(newCandidatesTable);
I cannot figure out why this is happening and I am using Chrome for the browser. /
I am getting a cloneNode error Uncaught TypeError: Cannot read property 'cloneNode' of null at application.js:42
when I move my script into a javascript file. But the application works when the script is in the HTML page.
const candidatesTable = document.getElementById("candidates_example");
const newCandidatesTable = candidatesTable.cloneNode(true);
document.body.appendChild(newCandidatesTable);
I cannot figure out why this is happening and I am using Chrome for the browser. https://jsfiddle/sithanga/sd5qtcj3/2/
Share Improve this question asked Dec 8, 2018 at 16:49 SSSSSS 331 gold badge1 silver badge3 bronze badges1 Answer
Reset to default 6You are using document.body but your script is inserted in header, before executing any code on elements you should make sure they are existing on the page. Why it works when you insert it as script tag is you are inserting it at bottom.
e.g DOMContentLoaded event will be fired when all DOM content is loaded and ready to be interacted by your JS code.