Member-only story

Create ul and li in JavaScript

Pravin M
3 min readJul 27, 2024

--

Create ul and li in JavaScript

For more questions and answers visit our website at Frontend Interview Questions

Basic Concepts

To create and manipulate ul and li elements in JavaScript, we primarily use the Document Object Model (DOM) methods. The most commonly used methods include document.createElement, appendChild, and createTextNode.

Example: Creating a Static List

Let’s start with a simple example where we create a static unordered list with three list items.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Creating Lists with JavaScript</title>
</head>
<body>
<div id="list-container"></div>
<script src="scripts.js"></script>
</body>
</html>

JavaScript (scripts.js):

// Get the container where the list will be added
const container = document.getElementById('list-container');
// Create a ul element
const ul = document.createElement('ul');
// Create li elements
const items = ['Item 1', 'Item 2', 'Item 3'];
items.forEach(itemText => {
const li = document.createElement('li'); // Create a new li element
const textNode = document.createTextNode(itemText); // Create a text node
li.appendChild(textNode)…

--

--

Pravin M
Pravin M

Written by Pravin M

I am a frontend developer with 10+ years of experience Blog :- https://www.frontendinterviewquestions.com

No responses yet