In this article, as shown in the title of this article, ‘Remove list item HTML element using JQuery’, it is specifically written to describe the process on how to remove a HTML element called list item using JQuery. A specific line of snippet code made and inserted in the web page which is made as an example to demonstrate how to remove list item HTML element using JQuery is shown as follows :
$(this).remove();
It might be seen as simple as shown in the above line of code which consist of a one short line but in the reality as in the whole big picture, it can be executed solely based on that line of code only. The ‘$(this)’ part is referring to an element of list item HTML element which is going to be removed. It is obviously can be seen since after the ‘$(this)’ part, it is followed with a function or method called ‘remove()’. So, what kind of line of snippet code needed to be added in order for the above line of code works like a charm ?. Below is the complete snippet codes :
$('#list_selection_sample').on('click','li',function(){ $(this).remove(); });
In the above snippet code, it is obvious that the one referred with ‘$(this)’ code part is the list item element which exists inside a HTML element with the id of ‘list_selection_sample’. The HTML element which is meant to be the one with the id of ‘list_selection_sample’ is indeed an unordered list since it is the parent of list item HTML element. And from the above snippet code shown, the removal process is triggered by an click event of the list item.
The most important part is to define the unordered list or to select the unordered list HTML element which inside of it, there is the list item which is going to be removed. Below is the example of that unordered list contains the list item which is going to be removed :
<ul> <li value="PostgreSQL">PostgreSQL</li> </ul>
We might be imagine that the declaration or the definition of the unordered list which is meant to contain the list item HTML element will be only be seen as the snippet code above but sadly after attempting on several removal process it cannot be done by only defining those snippet code above. The unordered list need to be contained in another HTML element called ‘div’ as shown below :
<div> <ul id="list_selection_sample"> <li value="PostgreSQL">PostgreSQL</li> </ul> </div>
So, the list item which is going to be removed is the list item which is being clicked. To be more specific, it is the list item located in an unordered list with the id of ‘list_selection_sample’. And the list item itself must be located in another HTML element represent by a tag of ‘<div>’. It represents a division or a section in an HTML document. It is weird that the above snippet code doesn’t work in an unordered list HTML element which is declared or defined as a single entity only. It must be contained in the div HTML element.
One thought on “Remove list item HTML element using JQuery”