Empujé un <form> al archivo HTML mediante el archivo JS, y luego agreguéEventListener a este formulario, pero resultó un error: TypeError no detectado: no se pueden leer las propiedades de nulo (leyendo 'addEventListener').
Supongo que se debe a que este archivo JS está vinculado directamente al archivo HTML, lo que significa que el JS podría cargarse antes que el <form> .
¿Alguien puede decirme cómo resolver esto?
Los códigos JS están a continuación:
// skip to the input fields $start.addEventListener('click', function(){ $chooseStory.remove() const inputs = [] inputs.push(` <form id="form"> <label>Provide The Following Words</lable> `) // assign words of stories to names and placeholders of inputs // the input will automatically loop for as many as the words are for (const word of stories[$index.value].words) { inputs.push(` <input type="text" name='${word}' placeholder="${word}"> `)} inputs.push(` <button type="submit" id="submit"> Read Story </button> <code id="result"></code> </form> `) const inputsField = inputs.join('') $container.innerHTML += inputsField }) // retrieve value of the form const $form = document.getElementById('form') $form.addEventListener('submit', function(e){ e.preventDefault() })Debe usar la delegación de eventos en la que se adjunta un oyente a un componente principal que captura eventos de elementos secundarios a medida que "burbujean" el DOM.
// Adds a new form to the page function addForm() { const html = ` <form id="form"> <label>Provide The Following Words</lable> <input /> <button type="submit" id="submit">Read Story</button> <code id="result"></code> </form> `; // Add the new HTML to the container container.insertAdjacentHTML('beforeend', html); } function handleClick(e) { // In this example we just want to // to log the input value to the console // so we first prevent the form from submitting e.preventDefault(); // Get the id of the submitted form and // use that to get the input element // Then we log the input value const { id } = e.target; const input = document.querySelector(`#${id} input`); console.log(input.value); } // Cache the container, and add the listener to it const container = document.querySelector('#container'); container.addEventListener('submit', handleClick, false); // Add the form to the DOM addForm(); <div id="container"></div>