This script allows us to add an element (in this case an li) to the DOM when an anchor tag is clicked. And conversely, remove an element when a different anchor tag is clicked.
We start with an unordered list with 4 list items. I also gave it a specific id=”testList”. If you don’t give it an id, a new li will be added to every list on the page when you click the anchor link. We create a variable called ‘i’ that is equal to the the number of list items plus 1. Then, when the the anchor tag with id ‘add’ is clicked, we are creating (appending) a new list item containing the value of i (5). Next, we add one to i (i++ or i=i+1), therefore setting a new value to i of 6 (5+1). Now if we were to click the anchor tag with id ‘add’, we would create a new li with the value of i which is now 6, and i then becomes 1 greater (7), and so on.
We then add an anchor tag with an id of ‘remove’. When this is clicked, we are removing the last li with the .remove method on li:last. We then decrease the value of i by 1 (i– or i=i-1) in order to always maintain i’s value to be one greater than the number of list items showing on the page. If we didn’t add this last step, then the value of i would not necessarily match that of the number of list items plus 1. For example, if we had 9 list items, and clicked remove three times to show only 6 list items, then the next time we clicked ‘Add’, it would add an li with a value of 10 because the last time we defined i was adding one to it when the list size was nine. Therefore, we both add and subtract 1 from i each time a respective anchor tag is clicked.
View the source below for the code and comments.
<ul id="testList"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <a href="#" id="add">Add List Item</a><br /> <a href="#" id="remove">Remove List Item</a>