How to Add Commas Between a List of Items Dynamically in JavaScript?


We can use the CSS "::before" pseudo-element to dynamically add a comma before each list item, except for the first one. By targeting the list item and using the "content" property, we can insert a comma before the list item's content. Additionally, we can use the ":not(:first-child)" pseudo-class to ensure that only the non-first list items have the comma added.

Consider we have the following HTML DOM:

<ul class="dynamic-list">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

We will discuss two different approaches in this article that can be used to achieve the same end goal: adding a comma after each list item (except the last item).

Therefore, let’s go through each of the approaches one by one.

Approach 1: Using CSS

One way to add commas between a list of items dynamically with CSS is to use the ::before pseudo-element on the list items.

Inside the ::before pseudo-element of each li, except the first li child, we will add a comma and that will do the trick for us.

The code for doing so will be −

.dynamic-list li {
  display: inline-block;
}
.dynamic-list li::before {
  content: ", ";
}
.dynamic-list li:first-child::before {
  content: "";
}

This will add a comma and space before each list item, except for the first one. The first item will have no content before it, resulting in no comma before it.

Approach 2: Using JavaScript

Alternatively, you can also use javascript or jquery to dynamically add commas between the list items. Here we are going to use plain JavaScript to add commas between a list of items dynamically.

The code doing this will be −

var list = document.getElementById("dynamic-list");
var items = list.getElementsByTagName("li");
for (var i = 0; i < items.length; i++) {
   if (i > 0) {
      items[i].innerHTML = ", " + items[i].innerHTML;
   }
}

This code first selects the list by its id and then gets all the list items. Then it loops through each item and checks if it's not the first item, if it's not, it adds a comma and space before the item's content.

Example

The final piece of code will be −

<!DOCTYPE html>
<html>
<head>
   <title>Comma Separated List</title>
</head>
<style>
   li {
      display: inline-block;
      color: black;
   }
</style>
   <body>
      <ul id="dynamic-list">
         <li>Item 1</li>
         <li>Item 2</li>
         <li>Item 3</li>
         <li>Item 4</li>
      </ul>
      <script>
         var list = document.getElementById("dynamic-list");
         var items = list.getElementsByTagName("li");
         for (var i = 0; i < items.length; i++) {
            if (i > 0) {
               items[i].innerHTML = ", " + items[i].innerHTML;
            }
         }
      </script>
   </body>
</html>

Updated on: 06-Feb-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements