Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!