最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read property 'cloneNode' of null, but works when the script is on HTML - Stack Overflow

programmeradmin2浏览0评论

I am getting a cloneNode error Uncaught TypeError: Cannot read property 'cloneNode' of null at application.js:42when 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:42when 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 badges
Add a ment  | 

1 Answer 1

Reset to default 6

You 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论