How to manipulate an HTML element created by Template literals?

0

Does anyone know why when you create an HTML component using the Template literals it always returns null? ex: I created a list and I want to get the li to put an event, but it always returns null, since it exists in the DOM.

const $container = doc.querySelector('[data-js="container"]');
const $categorie = doc.querySelectorAll('[data-js="categorie"] li');

 const markup = '
    <ul data-js='categorie'>
      <li>item</li>
      <li>item</li>
      <li>item</li>
    </ul>
 ';

 $container.innerHTML = markup;
    
asked by anonymous 13.10.2017 / 04:20

1 answer

0

Your problem is in the order of execution, you should perform the search for the elements, after they are created in DOM , put this line:

const $categorie = doc.querySelectorAll('[data-js="categorie"] li');

Below this:

$container.innerHTML = markup;

Example

const doc = document;
const $container = doc.querySelector('[data-js="container"]');

const markup = '
    <ul data-js='categorie'>
      <li>item 01</li>
      <li>item 02</li>
      <li>item 03</li>
    </ul>
';

$container.innerHTML = markup;

const $categorie = doc.querySelectorAll('[data-js="categorie"] li');

Array.from($categorie).forEach(item => {
    item.addEventListener('click', function(event) {
        alert("Você clicou em: " + this.innerText);
    });
});
<div data-js="container"></div>
    
13.10.2017 / 05:48