0

I have created form nodes with template string but i need to work them on change. I have tried .on('DOMNodeInserted') but i haven't managed to catch the event. I also tried to work with promises, but i dont know if its possible to work on html nodes with promisses. Is there a way to trigger a event listener on a html object that have been appended later?

here is one of my many tries

$('.body').on('DOMNodeInserted', function(e) {
if($(e.target).children()[0] !== undefined){
    let tema = $(e.target).children()[0].id;
    tema.onchange = () => {
        let el = manage(tema);
        console.log(el);
    }
}});

I

Vic
  • 1

1 Answers1

0

Here's an example of catching events from dynamically inserted elements. It uses "event delegation" - attaching a listener to a parent element to catch events from child elements as they bubble up the DOM.

// I've used `container` here but you could use any element
// you like. Just add a change listener to it identifying the
// function that needs to be called when it's triggered
const container = document.querySelector('#container');
container.addEventListener('change', handleChange, false);

const html = `
  <form>
    <input name="input1" type="text" placeholder="input1" />
    <input name="input2" type="text" placeholder="input2"/>
  </form>
`;

container.insertAdjacentHTML('beforeend', html);

function handleChange(e) {

  // The `event target` is whatever element has caused the change
  // listener to trigger. Here I've grabbed the name from the element
  // using destructuring and logged it to the console
  const { name } = e.target;
  console.log(name);
}
<div id="container"></div>
Andy
  • 61,948
  • 13
  • 68
  • 95