如何在 PopUp Modal 中使用 querySelector

How to use querySelector in a PopUp Modal

const pokemonContainer = document.getElementById('pokemonContainer');

pokemonContainer.innerHTML += `
<div>
    <section class="all-comments"></section>
</div>
`;

const allComments = document.querySelector('.all-comments');
allComments.appendChild(<h1>Hello World</h1>);
<div class="row" id="pokemonContainer"></div>

我正在尝试 querySelector('.all-comments') 但因为它在 pokemonContainer 中,所以它返回未定义。有人可以指导我如何查询 select 上面给出的放在 innerHTML 中的东西吗?

Node.appendChild() expects a node element as parameter, you can create a text node using Document.createTextNode():

allComments.appendChild(document.createTextNode('Hello World'));

演示:

const pokemonContainer = document.getElementById('pokemonContainer');

pokemonContainer.innerHTML += `
<div>
    <section class="all-comments"></section>
</div>
`;

const allComments = document.querySelector('.all-comments');
allComments.appendChild(document.createTextNode('Hello World'));
<div class="row" id="pokemonContainer"></div>

更新: 您不能将 <h1>Hello World</h1> 直接传递给 appendChild()。首先你需要创建一个你想要的类型的节点,然后设置文本,最后将该节点传递给方法。

或: 您可以尝试使用 Element.insertAdjacentHTML()

const pokemonContainer = document.getElementById('pokemonContainer');

pokemonContainer.innerHTML += `
<div>
    <section class="all-comments"></section>
</div>
`;

const allComments = document.querySelector('.all-comments');
allComments.insertAdjacentHTML('beforeend', '<h1>Hello World</h1>');
<div class="row" id="pokemonContainer"></div>