How to add list items to an existing unordered list (ul) using jQuery?

Learn to add new list items to an already existing unordered list in the document using jQuery?
Submitted by Pratishtha Saxena, on December 18, 2022

There are two types of lists in HTML – Ordered List (OL) and Unordered List (UL). The Ordered List represents a list that follows a particular order and is sequential. On the other hand, an Unordered List is a list without any order or sequence, that is, it follows bullet points to make a list. These two lists are declared by <ol> and <ul> tags respectively. The list items within this list are defined using <li> tag.

Now, to add new items on every click of a button using jQuery, we need to consider the append() method for the same.

Using .append() Method

The word 'append' signifies to add on something to an already provided content. Therefore, the append() method appends the specified content to the selected element. That means it will add the content after the element.

Syntax:

$("selector").append('Content', function());

This method takes in two parameters – content & function. The content is a necessary parameter and has to be specified that you wish to append after the selected element. The function is an optional parameter, which can be declared according to the need.

The content that is declared can contain HTML tags, DOM elements, jQuery objects, etc. Here, the content is a new list item defined using <li> tag.

jQuery code to add list items to an existing unordered list (ul)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <title>Document</title>
    <style>
      li{
      border: 1px solid black;
      width: 150px;
      margin: 2px;
      padding-left: 10px;
      color: darkgreen;
      }
    </style>
  </head>
  
  <body>
    <h2>Add List Items to an Existing Unordered List</h2>
    <h4>Click the button to add new list items in the given list.</h4>
    <button>Add Items</button>
    <hr>
    <ul>
      <li>January</li>
      <li>February</li>
      <li>March</li>
    </ul>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            $('ul').append('<li>New Month</li>');
        });
    });
  </script>
</html>

Output:

Example 1: How to add list items to an existing unordered list (ul) using jQuery?

Example 2: How to add list items to an existing unordered list (ul) using jQuery?




All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.