screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic UL and LI with JSON</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> </head> <body> <div id="dynamic-list"></div> <script> $(document).ready(function () { // Sample JSON data var jsonData = { "categories": [ { "name": "Fruit", "items": ["Apple", "Grapes", "Banana"] }, { "name": "Vegetables", "items": ["Carrot", "Broccoli", "Spinach"] }, { "name": "Dairy", "items": ["Milk", "Cheese", "Yogurt"] }, { "name": "Snacks", "items": ["Chips", "Popcorn", "Nuts"] }, { "name": "Beverages", "items": ["Water", "Soda", "Tea"] } // Add more categories and items as needed ] }; // Get the reference to the container div var dynamicList = $('#dynamic-list'); // Create an object to store the category elements var categoryElements = {}; // Iterate over each category in the JSON data $.each(jsonData.categories, function (index, category) { // Check if a <ul> element for the category already exists if (!categoryElements[category.name]) { // If not, create a new <ul> element with the category name bold categoryElements[category.name] = $('<ul>').append($('<li>').html('<b>' + category.name + '</b>')); } // Iterate over each item in the category and append <li> elements $.each(category.items, function (index, item) { categoryElements[category.name].append($('<li>').text(item)); }); }); // Append all category <ul> elements to the container div $.each(categoryElements, function (categoryName, categoryUl) { dynamicList.append(categoryUl); }); }); </script> </body> </html>