如何在弹窗Modal中使用querySelector选取innerHTML动态插入的元素
问题原因
你遇到的问题通常由以下两个原因导致:
- JS 代码执行时机早于 DOM 加载完成:如果你的脚本放在
<head>标签中,执行document.getElementById('pokemonContainer')时,页面还没渲染出 id 为pokemonContainer的节点,导致第一步就拿到了null,后续的innerHTML操作根本没执行,自然找不到.all-comments元素。 appendChild参数错误:你直接把 HTML 标签作为参数传入appendChild方法,该方法仅接收 DOM 节点对象,传入非节点参数会直接抛出语法错误。
修复方案
首先确保脚本在 DOM 加载完成后执行,其次修正 appendChild 的传参逻辑,修改后的代码如下:
HTML 代码
<div class="row" id="pokemonContainer"></div> <!-- 建议把脚本放在body末尾,保证DOM已经渲染完成再执行JS --> <script src="你的脚本路径"></script>
JS 代码
const pokemonContainer = document.getElementById('pokemonContainer'); // 动态插入内容 pokemonContainer.innerHTML += ` <div> <section class="all-comments"></section> </div> `; // 此时可以正常获取动态插入的元素 const allComments = document.querySelector('.all-comments'); // 先创建h1节点再传入appendChild const titleNode = document.createElement('h1'); titleNode.textContent = 'Hello World'; allComments.appendChild(titleNode);
如果必须把脚本放在 <head> 中,可以把 JS 逻辑包裹在 DOMContentLoaded 事件回调中,确保 DOM 加载完成后再执行:
document.addEventListener('DOMContentLoaded', function() { const pokemonContainer = document.getElementById('pokemonContainer'); pokemonContainer.innerHTML += ` <div> <section class="all-comments"></section> </div> `; const allComments = document.querySelector('.all-comments'); const titleNode = document.createElement('h1'); titleNode.textContent = 'Hello World'; allComments.appendChild(titleNode); });
内容的提问来源于stack exchange,提问作者Zain
相关产品推荐
相关产品推荐

