Create ul and li tags dynamically using JSON data and jQuery

← PrevNext →

In this article, I’ll show you how to create <ul> and <li> tags (or elements) dynamically in jQuery using JSON data. Using jQuery, I’ll extract JSON data from a file using a URL and use the data to create ul and li elements for a Hoverable dropdown menu with submenu.

image

create ul and li elements dynamically using json data and jquery

The JSON data

Here’s the sample JSON data. It has a list of birds with ID, Name and Type. Distinct bird types will serve as "menus" and the names will form the "sub-menus".

By the way, you can even do this using plain old JavaScript. Check this article.

The Markup

In the <body> section, I have defined a <ul> tag, which is the parent ul element. The Lis and subsequent Uls and Lis will be created dynamically in the below script.

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  <ul id="menu1"></ul>
</body> 
</html>
The jQuery Script
<script>
  $(document).ready(function () {
    
    // Top (header) list item.
    let li = $('<li/>').appendTo('#menu1');

    $('<a />')
      .text('Birds')
      .attr('href', '#')
      .appendTo(li);     // add the header (<ul>).

    // Create sub ul.
    let sub_ul = $('<ul/>').appendTo(li);    

    let arrData = [];
    $.getJSON('../../library/birds.json', function (data) {
      let typeOfBirds = [];

      $.each(data, function (index, value) {
        typeOfBirds.push(value.Type);
        arrData = data;
      });
      
      // Remove duplicates from the array, because we want unique types.
      typeOfBirds = Array.from(new Set (typeOfBirds));
      
      $.each(typeOfBirds, function (index, value) {
        // Create and add sub list items.
        let sub_li = $('<li/>').appendTo(sub_ul);
        $('<a />')
          .text(value + ' + ')
          .attr('href', '#')
          .appendTo(sub_li);
        
        $.each(arrData, function (i, v) {
          if (v.Type === value) { 
            // Create sub ul.
            let sub_sub_ul = $('<ul/>').appendTo(sub_li);
            let sub_sub_li = $('<li/>').appendTo(sub_sub_ul);
            $('<a />')
              .text(v.Name)
              .attr('href', '#')
              .appendTo(sub_sub_li);
          }
        });
      });
    });
  });
</script>
Try it

After creating the top <li> tag (Birds) and appending it to the parent <ul> element, I am extracting JSON from a url using $.getJSON() method, for the remaining <ul> and <li> tags.

You may also likeHow to create Cascading SELECT dropdown using JSON data and jQuery

← PreviousNext →