Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
How to get an id from inside of a template using DOM?

So i have a template setup and a form inside of it,

how can i get the id of the form since i need to access the form to get to the submit button for event handling.

<template id ="Request">
    <form id="add">
        <label>Name
           <input type="text" name="name" required/>
        </label>
        <label>Price
           <input type="text" name="price" required/>
        </label>
          <input type="submit" value="Add"/>
    </form>
</template>

Heres what i tried using the browsers command line

document.querySelector('#request > add');
     returns null
document.getElementById('request').querySelector("#add [name=name]");
     returns null
document.querySelector("#request").getElementById("add")
     function does not exist

Closest i got is this

document.querySelector("#request").content.getElementById("add")

This returns the content of the add section but i plan on adding a eventlistener to it and "content" does not want to work with it. Is there any alternatives to it?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The content within a <template> HTML element is a Document Fragment and therefore is not queryable from the root document in the same way that children of typical HTML elements are.

Instead of trying to add an event listener to a child of our <template>, we instead want to wait until the content of our template is rendered into the DOM.

Based on the code example you shared at https://jsfiddle.net/mhk4z0wL/, we would add the event listener just after the call to append the cloned helpTemplate.content:

data.appendChild(helpTemplate.content.cloneNode(true));
        
data.querySelector('#add').addEventListener('submit', () => {
  alert('I caught your submit!');
  e.preventDefault();
});

This will work, but it is not ideal. Every time that the user changes the rendered page to one other than Help by clicking one of the other page buttons, our Help form will be removed from the DOM. In this case it is best to remove our event listener in order to prevent memory leakage. We could do this by creating a reference to our submit handler callback function and making sure to remove it within each page rendering handler:

function onSubmitHelpForm(e) {
  alert('I caught your submit!');
  e.preventDefault();
}

function clearOnSubmitListener() {
  const helpForm = document.getElementById('add');

  if (helpForm) {
    helpForm.removeEventListener('submit', onSubmitHelpForm);
  }
}

And then within each button click handler we would have: clearOnSubmitListener();

For an example of how this would work, see this fiddle.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda