How to sort Unordered list with array index

I'm trying to reorder the list with data attributes kindly see the below code.

<ul>
<li data-block="block1">Some Text...</li>
<li data-block="block2">Some Text...</li>
<li data-block="block3">Some Text...</li>
<li data-block="block4">Some Text...</li>
</ul>

In my jQuery Array I have following values

values = array("block2","block1","block4","block3");

So I need to sort/reorder the list in the way of array index like below.

<ul>
<li data-block="block2">Some Text...</li>
<li data-block="block1">Some Text...</li>
<li data-block="block4">Some Text...</li>
<li data-block="block3">Some Text...</li>
</ul>

Kindly help me to get the proper solution.

Answers 1

  • You can utilize .html() , .map() , Attribute Equals Selector [name="value"]

    var values = Array("block2","block1","block4","block3");
    $("ul").html(values.map(function(val) {return $("[data-block="+val+"]")}))
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
    </script>
    <ul>
      <li data-block="block1">Some Text...1</li>
      <li data-block="block2">Some Text...2</li>
      <li data-block="block3">Some Text...3</li>
      <li data-block="block4">Some Text...4</li>
    </ul>


Related Articles