Reputation: 93
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>
I'm trying querySelector('.all-comments') but as it's in pokemonContainer that's why It's returning undefined. Someone can please guide me on how to query select something placed in innerHTML as given above?
Upvotes: 1
Views: 3267
Reputation: 68933
Node.appendChild()
expects a node element as parameter, you can create a text node using Document.createTextNode()
:
allComments.appendChild(document.createTextNode('Hello World'));
Demo:
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>
Update: You cannot pass <h1>Hello World</h1>
directly to appendChild()
. First you need to create a node of the type you want, then set the text, finally pass that node to the method.
OR: You can try using 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>
Upvotes: 2