如何编辑跨HTML嵌入的div文本?DOM访问报错求助
我有popup.html和popup_error.html两个HTML文件,已经通过object标签把popup_error.html的内容嵌入到popup.html的inner-body div里。但尝试访问并修改popup_error.html里的error-code div文本时,出现错误:
TypeError: Cannot set properties of null (setting 'innerText')
我猜测是DOM未完全加载,于是尝试用document.getElementById('inner-body').addEventListener('DOMContentLoaded', function() {}),结果又抛出错误:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
目前代码能正常添加并显示popup_error.html的内容,但就是改不了error-code的文本,求解决办法!
popup.js
/*Set div innerbody of popup.html to popup_error.html*/ document.getElementById('inner-body').innerHTML = '<object style="height: 100%" type="text/html" data="../layout/popup_error.html" ></object>' /*Set error-code*/ document.getElementById("error-code").innerText="404 Not found" //Failed
popup.html
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="../styles/popup.css"> <script src="../scripts/popup.js"></script> </head> <body> <div id="inner-body"> <div id="header-3"> Loading...</div> <div id="text-1">Getting information</div> </div> </body> </html>
popup_error.html
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="../styles/popup.css"> <script src="../scripts/popup.js"></script> </head> <body> <div id="error-code">Error: Code</div> </body> </html>
解决建议
问题核心
- 嵌入的
object是独立的文档环境,主页面的document无法直接访问其内部DOM元素。 - 原代码执行时机过早:主页面DOM还没完全渲染就去获取
inner-body,或者object内部内容还没加载就去查找error-code,自然会返回null。
- 嵌入的
具体修复步骤
监听
object加载完成事件
创建object元素并监听load事件,在回调里访问内部文档修改内容:document.addEventListener('DOMContentLoaded', function() { const innerBody = document.getElementById('inner-body'); innerBody.innerHTML = ''; const obj = document.createElement('object'); obj.style.height = '100%'; obj.type = 'text/html'; obj.data = '../layout/popup_error.html'; obj.addEventListener('load', function() { // 兼容不同浏览器获取内部文档 const innerDoc = obj.contentDocument || obj.contentWindow.document; innerDoc.getElementById('error-code').innerText = '404 Not found'; }); innerBody.appendChild(obj); });移除重复的脚本引入
popup_error.html里不需要引入popup.js,否则会导致主页面代码重复执行,引发额外问题,直接删掉该页面的<script>标签。确保主页面DOM加载完成再执行代码
把主页面的<script>标签移到body末尾,或者用DOMContentLoaded包裹所有逻辑,避免提前执行找不到DOM元素。
内容的提问来源于stack exchange,提问作者James

