Menggunakan di JavaScript untuk membuat formulir
//In this section, we will use a <template> element to hide our form. We will also show our form and render our to-do list using JavaScript.
//First, let’s see how to hide the form. In the HTML boilerplate, paste this code within the body element.
<div class="container">
<button type="button" onclick="showForm()" class="show-form">Show Form</button>
<!-- html template tag starts here -->
<template id="todo-input">
<div class="wrapper">
</div>
</template>
<!-- html template tag ends here -->
</div>
//Remember, using a <template> makes it very clear that the HTML inside of it needs JavaScript to render content dynamically. Here, we used the tag to hide our content.
//Showing a very basic form
//Now, let’s display our form with Javascript. In your script file, add the following.
if("content" in document.createElement("template")) {
// your code here
} else {
Fetching and rendering user’s todo list
alert("Your browser does not support template element!");
}
//Here, we test if the browser supports the HTML template element by checking the presence of the template element’s content attributes. Within the if statement block, paste this code.
function showForm() {
// Selecting the elements
const template = document.getElementById("todo-input");
const clone = template.content.cloneNode(true);
document.querySelector('.container').appendChild(clone);
template.innerHTML = "";
}
//In the showForm code block, we start by getting a reference to our <template> element using its ID and store this in a variable named template.
//Line 4 - We are not manipulating anything within the template so we just created a copy of its content template.content.cloneNode(true) and added this to the document.querySelector('.container').
//Line 8 - As we know, the template tag has methods for copying the content inside it so it can be repeatedly added to the DOM. Since we don’t want our form to be duplicated if the show form is clicked more than once. We set the innerHTML to an empty string.
//By clicking on the show form, our form will display.
OHIOLee