Home > OS >  Correct way to insert new LI-s into OL-s list from JS arr
Correct way to insert new LI-s into OL-s list from JS arr

Time:07-20

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" >
  <li id="name">apartment</li>
</ol>

<ol id="hhh" >
  <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>)?

CodePudding user response:

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" >
  <li>apartment</li>
</ol>

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

CodePudding user response:

First, document.getElementById assumes that the document contain elements of unique ids only. So, when document.getElementById('hhh'), it returns the first element always which in this case it is

<ol id="hhh" >
  <li id="name">apartment</li>
</ol>

You can instead use document.getElementsByClassName('specs').forEach().

For more info:

  1. https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
  2. https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
  • Related