1
      document.querySelector('#movies').innerHTML = `
        <div class="row">
          <div class="alert alert-primary w-50 mb-2" role="alert">
            New genre added.
          </div>
        </div>
        <div class="row">
          <div class="card mb-2 w-50">
            <div class="card-body">
              <h5 class="card-title">${name}</h5>
            </div>
          </div>
        </div>
      `;

From the code snippets, I am trying to select those elements with .card-title class

  const cardsList = document.querySelectorAll('.card-title');
  console.log(cardsList);

but it keeps on returning an empty NodeList.

Is it really not possible to target those elements added using innerHTML property after the DOM has been created and the page already loaded?

arantebw
  • 93
  • 2
  • 8
  • https://stackoverflow.com/questions/11716713/how-to-target-elements-set-from-innerhtml-or-html-using-jquery – s.kuznetsov Dec 04 '20 at 08:17
  • 2
    Please add a [mcve] preferable as [snippet (`<>`)](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) – Andreas Dec 04 '20 at 09:16

1 Answers1

2

No special treatment is needed. Nodes, once inserted, don't remember where they come from. Most likely, you're running query code before insertion actually happens.

const name = 'Your Name Here';
document.querySelector('#movies').innerHTML = `
  <div class="row">
    <div class="alert alert-primary w-50 mb-2" role="alert">
      New genre added.
    </div>
  </div>
  <div class="row">
    <div class="card mb-2 w-50">
      <div class="card-body">
        <h5 class="card-title">${name}</h5>
      </div>
    </div>
  </div>
`;

const cardsList = document.querySelectorAll('.card-title');
console.log(cardsList[0]);
<section id="movies">Loading...</section>
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • 1
    This answer gave me the idea that I am updating the ```innerHTML``` from a promise and I've isolated it in a function while I am selecting those elements upon page load. That is the reason why the ```NodeList``` is always empty. My bad! – arantebw Dec 04 '20 at 12:08