Today, I delved into JavaScript basics and managed to create a simple HTML page that allows users to add or remove list items. While I am aware that there are more advanced solutions out there, I believe that for my learning process, this accomplishment is significant.
// the function that adds a list item
function addListItem () {
var newLi = document.createElement("li");
newLi.className = "listItem";
// newLi.innerHTML = "<h3>List item</h3> <p>This is a simple list item</p>";
list.appendChild(newLi);
}
You can find the full code here: https://jsfiddle.net/l_wel/cuvc0m5g/
The dilemma lies in the initial function where I have included commented-out code. This code inserts HTML content inside the new list item. Is there a more efficient approach to achieving this? For instance, how can I make each new list item display its corresponding number?
- List item 1
- List item 2
- List item 3
and so forth...
I understand that implementing a counter might be the solution, yet I struggled with retaining the original HTML content from the first list item without having to rewrite it within the function.
Apologies for any language errors and if you consider this issue trivial. I've spent hours trying to figure it out and hope that my explanation makes sense. Eliminating the comment section might also resolve the problem, depending on the project requirements.
P.S. I haven't dabbled in jQuery yet; therefore, I aimed to tackle this task using vanilla JavaScript.