Card from Javascript into HTML, there must be a better way (working)

Viewed 99

There must be a better, shorter way to generate many cards from javascript into HTML. This is the format to follow, it's working but can it be better?????

span{color: red;}
<div id="mycard"></div> 
  
var dateSpan = document.createElement('span')
var ul = document.createElement('ul')
var ol = document.createElement('ol')
var li = document.createElement('li');
var li2 = document.createElement('li')

dateSpan.innerHTML = '#3500';
li.textContent = 'Title of card ' 
li2.textContent = '"Small description"' 

li.appendChild(dateSpan);
li.appendChild(ul);
ul.appendChild(li2);
ol.appendChild(li);


var app = document.querySelector('#mycard');
      app.appendChild(ol)

enter image description here

Note: Yeah, you can add a '<b/r>' but the "Small description" should be stylish later on... :)

2 Answers

Create a function to generate html content and then call that function as many time as you want. For example

function generateList(title, description){
   var htmlVal = `<li>${title}<br>${description}</li>`;
   return htmlVal;
}

Then call the function however you like and append it to the element.

document.getElementById("myCard") += generateList("Title of Card #3500","Small description");

Where in your html there's an element with id "myCard"

You can create a class cardMaker and create instances with a for loop:

class cardMaker {
  constructor(n) {

    var dateSpan = document.createElement('span')
    var ul = document.createElement('ul')
    var ol = document.createElement('ol')
    var li = document.createElement('li');
    var li2 = document.createElement('li')

    dateSpan.innerHTML = '#3500' + n;
    li.textContent = 'Title of card ' 
    li2.textContent = '"Small description"' 

    li.appendChild(dateSpan);
    li.appendChild(ul);
    ul.appendChild(li2);
    ol.appendChild(li);

    var app = document.querySelector('#mycard');
    app.appendChild(ol)

    }
}


let cards = [];
for (let i = 0; i < 10; i++) {
  cards[i] = new cardMaker(i);
}

Related