ADDING NEW HTML ELEMENTS
Now it’s your turn to have a go at using the createElement and appendChild methods.
In your code, use the DOM and JavaScript to create a new HTML element when an existing element is clicked.
Using APIs like the DOM makes building apps easier.
1) Open up your text-editing program. Create a new HTML file called newelements.html. Code a < div > (with an id attribute) that contains text, like this:
<!DOCTYPE html> <html> <head> <title>New Elements</title> </head> <body> <div id="list">Click here to add item</div> </body> </html>
2) In your < head >, create a new function. Your code will look like this:
<head> <title>New Elements</title> <script> function addItem() { } </script> </head>
3) Now make your function create a new < div > using the createElement method. Store your new < div > in a variable and give the variable a name.
Then set the value of your new < div > to some text using the innerHTML property.
Your code will look like this:
<script> function addItem() { var newItem = document.createElement("div"); newItem.innerHTML = "New item"; } </script>
4) Add a final line to your function. Use getElementById to find the < div > in your < body >. Use the appendChild method to add the new < div > to the
< div > in your < body >. Your code will look like this:
<script> function addItem() { var newItem = document.createElement("div"); newItem.innerHTML = "New item"; document.getElementById("list").appendChild(newItem); } </script>
5) Now the only thing missing is the function call in the < body > of our code. Add the onclick attribute to the < div > in your < body >, so that when the
< div > text is clicked your addItem function is called.
Your code will look like this:
<body> <div id="list" onclick="addItem();">Click here to add item</div> </body>
6) Save your HTML file and open it in your browser.
When you click on the “Click here“ piece of text a new < div > will be added to your app every time you click.
But how do we add the button to our app? Keep reading…