Best way to generate a dynamically read with pure javascript

Asked

Viewed 205 times

2

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 several times dynamically, using javascript, I intend to receive a json and apply in all fields.

  • Search by element <template>

  • I didn’t understand how to start

2 answers

5


If you have a JSON in the form of Array, 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>

Note on compatibility of browsers:

The above Javascript code uses new features from Ecmascript 2015 (or ES6), as the statement const, strings template and the noose for...of.

With this, if you want to provide support to older browsers like IE, I will leave a translation of the code to 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:

2

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

const dadosJSON = [
    { nome: 'StackOverflow EN', url: 'https://stackoverflow.com/' },
    { nome: 'StackOverflow PT', url: '/' },
    { nome: 'User SOpt: 51214', url: '/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 browser compatibility on Caniuse.com.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.