JavaScript — Creating and Removing HTML Elements
In the previous article I covered how to add event listeners to differnt elements in a web page. When we would select one of the tasks on the to-do list, it would just strike it out with a line. I want to cover how to actually remove and add elements through JavaScript in this one. Lets go!
Here I have this <ul>. I’m going to simply gain a reference to it, then use the remove() to remove it. Like so,
Now that list of things is gone!
In the last article I set up a forEach loop that cycles through the list of li tags. I can use this logic to remove a specific list element like this:
Easy peezy. Now lets add some stuff.
In my HTML document, I’ve changed the text on my button to say “Add new To Do!”.
Here I’ve gotten a reference to my button, then added a click event listener on it and in the call back function, I’ve said to append the innerHTML of the ul. I’m just appending a new list element every time I click the button. Each list element will say “Something new.”
So thats all good, but.. theres another way!
the document has a method called createElement(). This allows you to create an element and then assign new text to it like this:
Here I’m creating a const called li and setting it equal to the createElement method. Then I access the textContent property of that element and set it to “Something new to do.” After that, I’m accessing the parent object (the ul) and using the append method. Now when I click the button, I get new li elements, just like before. The append method puts the newly created/appended element at the bottom of the parent.
We can also use the prepend method. This will add that element to the TOP of the parent. Like this:
So if you’ve been following along, you may have tried clicking on your newly added li tags and nothing is happening. This is because we assigned the eventListeners on the original tags at the start. When the new ones are created, they arent being given event listeners. SO in the next article, I’ll be covering how to combat this using event delegation! See ya there!