Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
Correct way to insert new LI-s into OL-s list from JS arr

I have a few lists in HTML and an array of data in JS.

I want new <li>s to be created in each <ol> according to the first element of <li>.

const types = [{
    name: "house",
    sq: 250,
    year: 2020
  },
  {
    name: "apartment",
    sq: 70,
    year: 2010
  },
];

/*search key*/
document.querySelectorAll('.specs').forEach(ol => {
  const name = ol.querySelector("#name").textContent;
  const search = name;

  /*object search*/
  const res = () => {
    let result = []
    for (const item of types) {
      if (item.name.includes(search)) {
        return item;
      }
    }
    return result
  }

  /* THIS SHOULD ADD NEW LIs */
  var x = document.createElement("LI");
  var t = document.createTextNode(`${res().sq}`);
  x.appendChild(t);
  document.getElementById("hhh").appendChild(x);

});
<ol id="hhh" class="specs">
  <li id="name">apartment</li>
</ol>

<ol id="hhh" class="specs">
  <li id="name">house</li>
</ol>

What I have now is: that new <li>s are created in the first <ol> only.
The wrong result is shown here:

the wrong result is shown here

how can I fix it, to make each <li> element be created in the right place (<ol>)?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Note that IDs have to be unique! You using multiple IDs multiple times. Because of that, your element will always be included in the first element with the ID hhh.

To solve this, you need to give both ul an unique ID. The easiest way would be to use as the ID the name key:

const types = [{
    name: "house",
    sq: 250,
    year: 2020
  },
  {
    name: "apartment",
    sq: 70,
    year: 2010
  },
];

for (let i = 0; i < types.length; i++) {
  let el = types[i].name;
  let sq = types[i].sq;
  let year = types[i].year;
  document.querySelector(`#${el}`).insertAdjacentHTML('beforeend', `<li>${sq}</li>`);
  document.querySelector(`#${el}`).insertAdjacentHTML('beforeend', `<li>${year}</li>`);
}
<ol id="apartment" class="specs">
  <li>apartment</li>
</ol>

<ol id="house" class="specs">
  <li>house</li>
</ol>

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda