How to convert comma separated text in div into separate lines with JavaScript?

Let’s say the following is our comma separated text in div −

<div class="commaSeparated">

To convert comma separated text into separate lines, you need to use trim() along with split() on the basis of comma(,).


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<link rel="stylesheet" href="//">
<script src=""></script>
<script src=""></script>
<div class="commaSeparated">
   var allTheData = document.querySelector('.commaSeparated').textContent.trim().split(',')
   var separateList = '<ul>'
   allTheData.forEach(function(value) {
      separateList += '<li>' + value + '</li>';
   separateList += '</ul>';
   document.querySelector(".commaSeparated").innerHTML = separateList;

To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.


This will produce the following output −