How to create and remove HTML elements using jQuery

There may come a time when you want to add and remove HTML items on the fly. Because jQuery is just javascript, these changes are only on the client side. If the page were to be refreshed, the page would go back to it’s original form.

There are two main methods in jQuery that we will be using. These methods are called:

appendTo()

remove()

This lesson we’ll create a new un-ordered and have two links on the page. One will add items, and the other will remove the list items.

Let’s look at the code:

xhtml

jQuery

Ok. Let’s go over the source code.

xhtml

You might have wondered why I bothered to wrap <p> tags around my Anchor tags. It’s amazing that more people don’t realize this. In xhtml the spec says you have to have Anchor tags wrapped in a block level element.

jQuery

As far as the Jquery code goes let’s see how it reads:

Line 1 – When the document is ready run some jQuery Code.

Line 2 – Find out how many List items are in the unordered list with the class of menu.

Line 3 – When the anchor tag with the class of addItem is clicked run some code

Line 4 – Because we are adding an item we must make sure that we increment “I” before we output anything

Line 5 – We are still in the same section of running code. We’re going to at a new List item. We are outputing the variable i . It’s important that you don’t include it in the ‘’. Otherwise the code out output I as a text instead of the variable value.

Line 6 – End running code if addItem was clicked.

Line 7 – If the anchor tag with a class of removeItem was clicked then run some code

Line 8 – It’s always good to put safety measures in place. You can’t have negative amounts of list items. I’m testing what “I” is before I do anything.

Line 9 – As long as “I” is greater or equal to one we can remove a list item we can proceed.

Line 10 – Let’s first update “I” by removing 1.

Line 11 – Go to the last list item in the menu class and remove that item.