Home > Software design >  I want to put the contents of arrays into h3 element then put it into their its containers
I want to put the contents of arrays into h3 element then put it into their its containers

Time:12-02

I have an array containing 10 arrays, and put one array into each of its containers, creating an h3 containing the contents of that array. but what happens is that all arrays go into all their containers. You can see the example below

.list-container {
  width: 300px;
  background: royalblue;
  padding: 1em;
  margin: 2rem;
}
h3 {
  display: inline-block;
  font-size: .75rem;
  color: white;
  padding: .75em;
  background: red;
  margin: .75rem;
}
/* this is exempla style */
.example {
  width: 300px;
  background: royalblue;
  padding: 1em;
  margin: 2rem;
}
<div class="list-container">
  </div>
  <div class="list-container">
  </div>

  <!-- this are the examples -->
  <h2>below is the correct example</h2>
  <div class="example">
    <h3>Frontend</h3>
    <h3>Senior</h3>
    <h3>HTML</h3>
    <h3>CSS</h3>
    <h3>JavaScript</h3>
  </div>
  <div class="example">
    <h3>Fullstack</h3>
    <h3>Midweight</h3>
    <h3>Python</h3>
    <h3>React</h3>
  </div>
const arrList = [
        ["Frontend", "Senior", "HTML", "CSS", "JavaScript"],
        ["Fullstack", "Midweight", "Python", "React"]
];
        const listContainer = document.querySelectorAll('.list-container');
        listContainer.forEach(container => {
          
          arrList.forEach(list => {
            
            
              const h3 = document.createElement('h3');
              h3.innerHTML = list;
            container.append(h3);
          });
          
        });

CodePudding user response:

You should choose which arrays content you would like to use based on the containers index, using the forEach function's index parameter:

const arrList = [
    ["Frontend", "Senior", "HTML", "CSS", "JavaScript"],
    ["Fullstack", "Midweight", "Python", "React"]
];

const listContainer = document.querySelectorAll('.list-container');
listContainer.forEach((container, index) => {
    arrList[index].forEach(list => {
        const h3 = document.createElement('h3');
        h3.innerHTML = list;
        container.append(h3);
    });
});
.list-container {
  width: 300px;
  background: royalblue;
  padding: 1em;
  margin: 2rem;
}
h3 {
  display: inline-block;
  font-size: .75rem;
  color: white;
  padding: .75em;
  background: red;
  margin: .75rem;
}
/* this is exempla style */
.example {
  width: 300px;
  background: royalblue;
  padding: 1em;
  margin: 2rem;
}
<div class="list-container">
 </div>
 <div class="list-container">
 </div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related