首页 > 解决方案 > 即使在等待网页加载时也未捕获类型错误

问题描述

将 JavaScript 加载到我的网页时出现此错误

未捕获的类型错误:无法将属性“contentEditable”设置为 null

但是,在执行此操作之前,我正在等待网页加载,因此我看不出错误的原因。

JavaScript:

window.onload = (function () {
  var doc = document.getElementById('doc');
  doc.contentEditable = true;
  doc.focus();
})();

HTML 片段:

<body>
    <header class="header">
      <h1 class="header__h1">editor</h1>
    </header>
    <div class="doc">
      <div class="doc__background-ribbon"></div>
      <div class="doc__text-editor hidden"></div>
    </div>
    <script src="myfilehereexample"></script>
</body>

标签: javascripthtml

解决方案


您没有带有idof的元素doc。它有一个class所以.getElementById是行不通的。将其更改为具有id或更改查询以搜索类(如下所示):

window.onload = (function () {
  var doc = document.querySelector('.doc'); // Query for the first element with a class of "doc"
  doc.contentEditable = true;
  doc.focus();
})();
    <header class="header">
      <h1 class="header__h1">editor</h1>
    </header>
    <div class="doc">Type here
      <div class="doc__background-ribbon"></div>
      <div class="doc__text-editor hidden"></div>
    </div>


推荐阅读