Best way to dynamically generate a li with pure javascript

1

Hello, I have the following structure

<li class="col-md-4">
<figure>
    <a class="list" href="#"><img alt="" src="image.png"></a>
    <div class="color">
        <small>teste</small>
        <span>post</span>
    </div>
 <figcaption>
    <div class="bar">
        <div class="progress"> <div style="width: 10%;" data-transitiongoal="10" role="pro-bar" class="pro-bar" aria-valuenow="20"><span>1080%</span></div> </div>
    </div>
        <div class="legeng">
            <div class="info">
                <h2><a href="">Titulo teste</a></h2>
                <p><img class="author" src="author.png">Nome</p>
            </div>
                <a href="" class="btn-bor readMore">Ver</a>
            </div>
 </figcaption>
</figure>

I would like a good example to generate it multiple times dynamically, using javascript, I want to get a json and apply in all fields.

    
asked by anonymous 11.06.2018 / 22:12

2 answers

5

If you have a JSON in the form of Array , you can iterate over the items and create a <li> using JavaScript:

const data = [{
  name: 'Adalbeto',
  age: 23
}, {
  name: 'Bdalbeto',
  age: 45
}, {
  name: 'Cdalbeto',
  age: 37
}];

// Elemento em que os itens da lista serão 'appendados':
const list = document.getElementById('userlist');

/**
 * Aqui iteramos sobre cada elemento da lista usando o laço for...of.
 * Consulte as referências da resposta.
 */
for (const user of data) {
  const el = document.createElement('li');
  el.innerText = '${user.name} - ${user.age}';

  list.appendChild(el);
}
<h1>Usuários - Idade</h1>
<ul id="userlist"></ul>

Browsers Compatibility Note:

The above JavaScript code uses new features from EcmaScript 2015 (or ES6 ) , such as the const statement, template strings and the for...of loop.

With this, if you want to provide support for old browsers, such as IE, I'll leave a translation of the code for ES5 :

var data = [{
  name: 'Adalbeto',
  age: 23
}, {
  name: 'Bdalbeto',
  age: 45
}, {
  name: 'Cdalbeto',
  age: 37
}];

var list = document.getElementById('userlist');

for (var index in data) {
  var user = data[index];
  var el = document.createElement('li');
  el.innerText = user.name + ' - ' + user.age;

  list.appendChild(el);
}
<h1>Usuários - Idade</h1>
<ul id="userlist"></ul>

Reference:

11.06.2018 / 22:42
2

You can use Template Strings . An example, using a very simple list:

const dadosJSON = [
    { nome: 'StackOverflow EN', url: 'https://stackoverflow.com/' },
    { nome: 'StackOverflow PT', url: 'https://pt.stackoverflow.com/' },
    { nome: 'User SOpt: 51214', url: 'https://pt.stackoverflow.com/users/51214' }
]

var dadosHTML = ''

dadosJSON.forEach(dado => {
    dadosHTML += '<li><a href='${dado.url}'>${dado.nome}</a></li>'
})

document.getElementById('dados').innerHTML = dadosHTML
<ul>
  <div id='dados'></div>
</ul>

See the compatibility with browsers in CanIUse.com .

CanIUse.com     

11.06.2018 / 22:19