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?
CodePudding user response:
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.