Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda