【问题标题】:How to use querySelector in a PopUp Modal如何在弹出模式中使用 querySelector
【发布时间】:2021-11-06 21:15:24
【问题描述】:

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>);
&lt;div class="row" id="pokemonContainer"&gt;&lt;/div&gt;

我正在尝试 querySelector('.all-cmets') 但由于它位于 pokemonContainer 中,这就是它返回未定义的原因。有人可以指导我如何查询上面给出的放在innerHTML中的东西吗?

【问题讨论】:

  • 我认为你应该使用 append 而不是 innerHTML
  • 您只需要使用适当的参数调用appendChild
  • @IlijaIličić 我无法改变这一点,因为这是一个结对编程活动,它是由其他人编写的

标签: javascript html dom dynamic queryselector


【解决方案1】:

Node.appendChild() 需要一个节点元素作为参数,您可以使用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'));
&lt;div class="row" id="pokemonContainer"&gt;&lt;/div&gt;

更新:您不能将&lt;h1&gt;Hello World&lt;/h1&gt; 直接传递给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>');
&lt;div class="row" id="pokemonContainer"&gt;&lt;/div&gt;

【讨论】:

  • 能否请您再次查看问题,因为我现在编辑了问题。将“hello world”替换为

    Hello World

    。它应该是 HTML 元素而不是文本节点。
  • @ZainSadaqat,为您在问题中所做的更新添加了另一个解决方案,请检查:)
  • 问题不在于 h1Node,而在于 allComments。我无法访问 allComments,因为它是动态生成的。
  • @ZainSadaqat,虽然我不太清楚这个问题,但您可以尝试使用insertAdjacentHTML() allComments.insertAdjacentHTML('beforeend', '&lt;h1&gt;Hello World&lt;/h1&gt;').....请检查更新的答案:)
  • appendChild 是我的次要要求。主要要求是我想从 innerHTML 部分查询选择。我做不到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多