How to iterate the div items in HTML, and assign the value to each one?

Viewed 66

I consumed an api created, where it will return a list with emails, I created a modal, with a div, where by the amount of emails returned, I want to add a div, and at the same time put the value of the emails in each one of them , the most I got was to put the same email in all of them, but at least I managed to add the amount of divs according to the number of emails returned, follows the code

<div class="modal">
    <h2>Lista</h2>
    <div id="list">
    </div>
</div>

modalList: (json) => {
        qS('.screen').style.justifyContent = 'center';
        qS('.screen').style.alignItems = 'center';
        qS('.rightside').style.display = 'none';
        qS('.modal').style.display = 'block';
        json.list.forEach((item, index)=>{
            let numeroHTML = ''
            for(let i = 0; i <= index; i++ ){
               numeroHTML += `<div class="result"></div>`;
            }
            qS('.modal #list').innerHTML = numeroHTML
            qSa('.result').forEach((result) => {
                result.innerHTML = item

            })
        });
    }

enter image description here

the logic that I'm not able to do is how to put each item in the array, that is, each email in a div only, and thus make a list in this modal

2 Answers

Details are commented in example below

/*
I'll assume the JSON is a typical array of objects and each object having a 
property/key "email" 
*/
const data=[{email:"tmcgowing0@netlog.com"},{email:"ckelsow1@usa.gov"},{email:"zwrench2@github.io"},{email:"avayne3@biblegateway.com"},{email:"mmarquis4@telegraph.co.uk"},{email:"pbrannigan5@marketwatch.com"},{email:"czannetti6@zimbio.com"},{email:"baspey7@thetimes.co.uk"},{email:"ejaumet8@tripadvisor.com"},{email:"pfellow9@cnbc.com"}];

/**
 * Renders a list in HTML from a given array of objects and a key.
 * @param {string<CSS>} selector - A CSS selector of the <ul>, <ol>, or <menu>
 * @param {array<object>} json - The data to make the list from
 * @param {string} key - The property/key to get the value from for the list
 */
const modalList = (selector, json, key) => {
  // Reference the list OR <body> (if undefined, null, etc)
  const node = document.querySelector(selector) || document.body;
  /*
  On each iteration through >json< render a htmlString into a <li> and add
  the current object's value of >key<
  */
  json.forEach(item => node.insertAdjacentHTML('beforeEnd', `<li>${item[key]}</li>`));
};

/*
"click" event handler registered to button.open. When triggered the modal opens
and modalList() is called
*/
document.querySelector('.open').onclick = e => {
  document.querySelector('.modal').showModal();
  modalList('ul', data, 'email');
};

/* The rest is unrelated to question */
const UI = document.forms.UI;

UI.onclick = modalUI;
UI.onsubmit = funcX;

function modalUI(e) {
  const OG = e.target;

  if (OG.matches('.close')) {
    document.querySelector('.modal').close();
  }
};

function funcX(e) {
  e.preventDefault();
  console.log(e.type + ' event fired');
};
html {
  font: 2ch/1.5 'Segoe UI'
}

html,
body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

main {
  width: 100%;
  height: 100%;
}

dialog {
  margin: 10px auto;
  min-height: 50%;
  width: 50%;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  width: 90%;
  padding-bottom: 5px;
  border-bottom: 2px ridge grey
}

menu {
  width: 90%;
  display: flex;
  justify-content: flex-end;
  align-items: flex-start
}

h3 {
  margin: 0 0 -8px 0;
}

.btn {
  display: inline-block;
  cursor: pointer;
  border-radius: 5px;
}

section {
  width: 90%
}

ul {
  list-style: none;
  margin-left: -35px
}

footer {
  width: 90%;
  border-top: 2px ridge grey;
}

.close {
  align-self: flex-start;
}
<main>
  <dialog class='modal'>
    <form id='UI'>
      <header>
        <h3>Email List</h3>
        <input class='btn close' type='button' value='X'>
      </header>
      <section>
        <ul></ul>
      </section>
      <footer>
        <menu>
          <button class='btn confirm'>Confirm</button>
          <button class='btn close' type='button'>Cancel</button>
        </menu>
      </footer>
    </form>
  </dialog>
  <menu>
    <button class='btn open'>Open Email List</button>
  </menu>
</main>

To create HTML from your array you can use a foreach loop like you're doing. You should be using the HTML <ul> element with <li>s inside. Do something like this for each iteration:

const element = document.createElement('li')
element.innerText = item
list.appendChild(element)

const json = {
  list: ["one", "two", "three"]
}

const listElement = document.querySelector('#list')
json.list.forEach((item, index) => {
  const element = document.createElement('li')
  element.classList.add('result')
  element.innerText = item
  list.appendChild(element)
});
<div class="modal">
  <h2>Lista</h2>
  <ul id="list">
  </ul>
</div>

Related