1

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

      <ul id="sortable1" class="connectedSortable">
          <li id="1" class="ui-state-default">A</li>
          <li id="2" class="ui-state-default">B</li>
          <li id="3" class="ui-state-default">C</li>
          <li id="4" class="ui-state-default">D</li>
          <li id="5" class="ui-state-default">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!

2 Answers 2

4

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" class="connectedSortable">
  <li id="1" class="ui-state-default">A</li>
  <li id="2" class="ui-state-default">B</li>
  <li id="3" class="ui-state-default">C</li>
  <li id="4" class="ui-state-default">D</li>
  <li id="5" class="ui-state-default">E</li>
</ul>

Sign up to request clarification or add additional context in comments.

1 Comment

it should be noted that querySelectorAll returns a Node List not an Array
3

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" class="connectedSortable">
          <li id="2" class="ui-state-default">B</li>
          <li id="1" class="ui-state-default">A</li>
          
          <li id="3" class="ui-state-default">C</li>
          <li id="4" class="ui-state-default">D</li>
          <li id="5" class="ui-state-default">E</li>
      </ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.