How to create ul li in JavaScript

In web development, JavaScript plays an important role in improving the functionality and interactivity of websites.

One of the frequent tasks that developers often encounter is creating an unordered list (ul) with list items (li) constantly using JavaScript.

Either you are a novice or an expert developer, this article will provide you with the fundamental knowledge to create ul li elements efficiently.

Why Create ul li in JavaScript?

While HTML provides the “<ul> and <li>” tags to make an unordered list, there are cases where you might need to simply generate and employ list items using JavaScript.

Here are the following common use cases:

  • Establishing a list based on user input or data fetched from an API.
  • Making dynamic navigation menus or dropdowns.
  • Creating a list of items from a database or external source.
  • Adding or removing list items based on the expected conditions or user interactions.

By constructing ul li elements rapidly in JavaScript, you have complete control over the content and action of the list.

This flexibility enables you to create dynamic and interactive web applications that can accommodate different scenarios.

How to Create ul li in JavaScript Using createElement() Method

One of the methods for creating ul li elements in JavaScript is by using the createElement() method.

This method enables you to create new HTML elements programmatically.

Here’s an example that uses createElement() method:

// Create the ul element
const unorderedList = document.createElement('ul');

// Create the li elements
const listItem1 = document.createElement('li');
const listItem2 = document.createElement('li');
const listItem3 = document.createElement('li');

// Set the text content of the li elements
listItem1.textContent = 'Product 1';
listItem2.textContent = 'Product 2';
listItem3.textContent = 'Product 3';

// Append the li elements to the ul element
unorderedList.appendChild(listItem1);
unorderedList.appendChild(listItem2);
unorderedList.appendChild(listItem3);

// Append the ul element to an existing HTML element
document.getElementById('myListing').appendChild(unorderedList);

In this example code, we create a new unordered List(ul) element and three list item(li) elements using with the createElement() method.

Then, we set the text content of each li element and append them to the ul element.

Finally, we append the ul element to the current HTML element with the ID “myListing“.

How to Create ul li in JavaScript Using innerHTML Property

Another method to creating ul li elements in JavaScript is by using the innerHTML property.

This property enables you to set the HTML content of an element as a string.

Here’s an example code that uses innerHTML property:

// Get the reference to an existing HTML element
const property = document.getElementById('myProperty');

// Set the HTML content using innerHTML
property.innerHTML = `
  <ul>
    <li>House 1</li>
    <li>House 2</li>
    <li>House 3</li>
  </ul>
`;

In this example code, we use the innerHTML property to set the HTML content of an existing element with the ID “myProperty“.

We provide the ul and li elements as a string, including the applicable content.

How to Create ul li in JavaScript Using Document Fragment

Using a document fragment will be a dynamic method for creating ul li elements in JavaScript, specifically when dealing with a large number of items.

A document fragment enables you to append different elements without affecting the main document’s performance.

Here’s an example that uses a document fragment:

// Create a document fragment
const fragmentExample = document.createDocumentFragment();

// Create and append the li elements
for (let x = 1; x <= 3; x++) {
  const listItem = document.createElement('li');
  listItem.textContent = `Item ${x}`;
  fragmentExample.appendChild(listItem);
}

// Create the ul element and append the fragment
const unorderedList = document.createElement('ul');
unorderedList.appendChild(fragmentExample);

// Append the ul element to an existing HTML element
document.getElementById('myFragment').appendChild(unorderedList);

In this example code, we make a document fragment and use a loop to create three li elements.

We set the text content of each li element and append them to the fragment. Then, we create the ul element and append the fragment.

Finally, we append the ul element to an existing HTML element with the ID “myFragment“.

How to Create ul li in JavaScript Using Template Literals

Template literals provide a proper method to create ul li elements in JavaScript by enabling you to integrate the expressions and multiline strings.

Here’s an example that uses template literals:

// Get the reference to an existing HTML element
const property = document.getElementById('myProperty');

// Define the list items as an array
const products = ['Item 1', 'Item 2', 'Item 3'];

// Create the ul element using template literals
const unorderdList = document.createElement('ul');
unorderdList.innerHTML = `
  ${products.map(products => `<li>${products}</li>`).join('')}
`;

// Append the ul element to the property
property.appendChild(unorderdList);

In this example code, we specify the list items as an array. Using template literals, we map over the array and make a li elements constantly.

The join(”) method is used to concatenate the li elements into a single string.

Finally, we create the ul element and set its innerHTML property to the rapidly generated string.

The ul element is appended to an existing HTML element with the ID “myProperty“.

How to Style the ul li Elements

Styling ul li elements created constantly in JavaScript follows the same principles as styling regular HTML elements.

You can apply CSS styles to the elements using different methods such as inline styles, CSS classes, or performing the element’s style property.

For example, to change the font color of the li elements created dynamically, you can use the following code:

// Get the reference to the dynamically created li elements
const listItemElements = document.querySelectorAll('li');

// Apply styles to the li elements
listItemElements.forEach(li => {
  li.style.color = 'green';
});

In this example code, we use querySelectorAll to select all the li elements that were created continually.

Then, we iterate over the selected elements and set the color property of their style object to “green“.

You can customize the styles according to your demands using CSS properties such as font-size, background-color, padding, etc.

FAQs

Can I add attributes to the dynamically created li elements?

Yes, you can add attributes to the dynamically created li elements using JavaScript.

How can I append the ul li elements to a specific HTML element?

To append the ul li elements to a specific HTML element, you can use the appendChild methodof the parent element.

Is it possible to dynamically remove an li element from the ul list?

Yes, it is possible to dynamically remove an li element from the ul list using JavaScript.

What if I want to add event listeners to the dynamically created li elements?

If you want to add event listeners to the dynamically created li elements, you can do this by selecting the elements and attaching the desired event listener function.

Are there any alternative libraries or frameworks that simplify the process of creating ul li elements?

Yes, there are different libraries and frameworks available that can simplify the process of creating ul li elements in JavaScript. Some popular options include jQuery, React, Angular, and Vue.js.

How can I iterate over an array and create corresponding li elements?

To iterate over an array and create corresponding li elements, you can use a loop or array methods like map or forEach.

Conclusion

In this article, we have discussed several methods to create ul li elements dynamically using JavaScript.

Either you choose to use the createElement() method, innerHTML property, document fragment, or template literals, each approach offers its own advantages and can be used based on your explicit requirements.

Additional Resources

Here are some additional tutorials that you can explore to further enhance your knowledge and skills about JavaScript:

Quick step-by-step summary (click to expand)
  1. Why Create ul li in JavaScript. Read the ‘Why Create ul li in JavaScript?’ section for the details and code.
  2. How to Create ul li in JavaScript Using createElement() Method. Read the ‘How to Create ul li in JavaScript Using createElement() Method’ section for the details and code.
  3. How to Create ul li in JavaScript Using innerHTML Property. Read the ‘How to Create ul li in JavaScript Using innerHTML Property’ section for the details and code.
  4. How to Create ul li in JavaScript Using Document Fragment. Read the ‘How to Create ul li in JavaScript Using Document Fragment’ section for the details and code.
  5. How to Create ul li in JavaScript Using Template Literals. Read the ‘How to Create ul li in JavaScript Using Template Literals’ section for the details and code.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Adones Evangelista


Programmer & Technical Writer at PIES IT Solution

Adones Evangelista is a programmer and writer at PIES IT Solution, author of over 900 tutorials and error-fix guides at itsourcecode.com. Specializes in JavaScript, Django, Laravel, and Python error debugging covering ValueError, TypeError, AttributeError, ModuleNotFoundError, and RuntimeError, plus C/C++ and PHP capstone projects for BSIT students.

Expertise: JavaScript · Python · Django · Laravel · Error Debugging · C/C++
 · View all posts by Adones Evangelista →

Leave a Comment