Home > Back-end >  How to convert the order of <li> in an unordered list into a JavaScript Array?
How to convert the order of <li> in an unordered list into a JavaScript Array?

Time:11-09

I have this unordered list which can be arranged by the user:

      <ul id="sortable1" >
          <li id="1" >A</li>
          <li id="2" >B</li>
          <li id="3" >C</li>
          <li id="4" >D</li>
          <li id="5" >E</li>
      </ul>

I wanted to make a Javascript array based on the arrangement for example if the order is ADBEC then the array should be [1, 4, 2, 5, 3]

An ID has been set for each <li> as an individual identifier.

Please note this refers to the orders of list items not the contents. All help appreciated thanks!

CodePudding user response:

You can use querySelectorAll to loop through each li and push the id to an array.

let sortable1 = document.querySelectorAll("#sortable1 li"),arry = [];

sortable1.forEach((e)=> arry.push(e.id))

console.log(arry)
<ul id="sortable1" >
          <li id="2" >B</li>
          <li id="1" >A</li>
          
          <li id="3" >C</li>
          <li id="4" >D</li>
          <li id="5" >E</li>
      </ul>

CodePudding user response:

the order is guaranteed to be from top to bottom, so:

document.querySelectorAll("#sortable1 li").forEach(function(li) {
  console.log(li.id)
})
<ul id="sortable1" >
  <li id="1" >A</li>
  <li id="2" >B</li>
  <li id="3" >C</li>
  <li id="4" >D</li>
  <li id="5" >E</li>
</ul>

  • Related