How to manipulate an HTML element created by Template literals?

Asked

Viewed 54 times

0

Does anyone know why when you create an HTML component using Template literals it always returns null? ex: I created a list and I want to take the li to put an event, but always returns null, since it exists in 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;
  • Note: The list becomes a nodeList and you could transform into array like with the Feature of the es6 the Array.from() without problems, but Zica is that the element created by the literals template does not exist in the DOM.

1 answer

0

Your problem is in the order of execution, you must perform the search for the elements, after they are created in the GIFT, put that 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>

  • Wellingthon, Thanks! That’s right, thanks a lot, I missed it yesterday.. Thanks a!!!

  • If possible mark as right or useful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.