Home > Net >  How to add List Items DOM from a JSON string in JS/Jquery
How to add List Items DOM from a JSON string in JS/Jquery

Time:07-02

data = [
{ "id" : "1", 
    "prepare" : "Hello welcome to xyz portal || 1. Please login to system || 2. Open dashboard || Verify your details and confirm."
    },
{ "id" : "2", 
    "prepare" : "Hello welcome to portal || a. Please click on link || b. Open the details list items || Check and confirm the details."
    }
]

I need to prepare HTML DOM from this JSON, like paragraph in P tag and numbered or alphabet items in list items. I am trying like below putting everything in P tag including number and alphabets.

But i need those number/alphabets to be placed inside ol/ul/li tags and type should display from list-style-type in css, please help me how can we do that..

var htmlArray = [];
for (i = 0 ; i< data.length ; i  ){
    var dataString= data[i].prepare.split("||");
    for(j = 0 ; j<dataString.length; j  ){
        var htmlString = "<p>" dataString[i] "</p>";
        htmlArray.push(htmlString);
    }
}

htmlDOM = "<div>" htmlArray.join('') "</div>";

CodePudding user response:

You can do following:

<ul id="jsonDiv"></ul>
<script>
  data = [
    {
      id: "1",
      prepare:
        "Hello welcome to xyz portal || 1. Please login to system || 2. Open dashboard || Verify your details and confirm.",
    },
    {
      id: "2",
      prepare:
        "Hello welcome to portal || a. Please click on link || b. Open the details list items || Check and confirm the details.",
    },
  ];
  var htmlArray = [];
  for (i = 0; i < data.length; i  ) {
    var dataString = data[i].prepare.split("||");
    for (j = 0; j < dataString.length; j  ) {
      var htmlString = "<p>"   dataString[j]   "</p>";
      htmlArray.push(htmlString);
    }
  }

  htmlDOM = "<div>"   htmlArray.join("")   "</div>";

  var targetDiv = document.getElementById('jsonDiv');
  targetDiv.innerHTML = htmlDOM;
</script>

CodePudding user response:

you can do something like this

const data = [
{ "id" : "1", 
    "prepare" : "Hello welcome to xyz portal || 1. Please login to system || 2. Open dashboard || Verify your details and confirm."
    },
{ "id" : "2", 
    "prepare" : "Hello welcome to portal || a. Please click on link || b. Open the details list items || Check and confirm the details."
    }
]

const container = document.getElementById('container')

const formatHtml = ([p,...li]) => `<p>${p}</p><ul>${li.map(l => `<li>${l}</li>`).join('')}</ul>`

const html = data.map(d => `<div>${formatHtml(d.prepare.split(' || '))}</div>`).join('')

container.innerHTML = html
<div id="container"></div>

  • Related