How to sort element by numerical value of data attribute using JavaScript?


Generally, we sort arrays, objects and some other data types using some method of JavaScript. But, in this article, we are going to sort the child elements of an element whose values are in unsorted order using the data attribute of those child elements.

In this article, we are going to learn about the two different ways or methods of sorting the child elements according to the value of their data attribute given to them.

The methods we use to sort are listed below −

  • By selecting the value of data attribute using the getAttribute() method.

  • By selecting the value of data attribute using the dataset.percentage property.

Let us discuss them one by one in details with the help of code examples associated with each method.

Using the getAttribute() method

The getAttribute() method is used to get the value given to the particular element that is passed inside its parenthesis. We can use this method to compare the values of the data attribute given to the child elements.

Syntax

Following syntax will show you how you can use the getAttribute() method to get the value of passed attribute −

var variable_name = selected_element.getAttribute(" attribute_name ");

Let us understand the practical implementation of getAttribute() method to sort the child elements according to their data attribute values.

Steps

  • Step 1 − In the first step of the algorithm, we will add a input element to the HTML document to get value of the child elements from user and set their data property as well as their content as that entered value.

  • Step 2 − In the next step, we will add a div element inside which we will dynamically add child elements with the help of JavaScript and then sort them with their data attribute value.

  • Step 3 − In this step, we will add two different buttons with different functionalities. The first button will add append the child elements to the div tag defined in previous step, while the second button will sort those child elements with according to their data attribute value.

  • Step 4 − In the fourth step, we will define a JavaScript function to assign it as a value to the onclick event of the first button defined in previous step. In this function, ae are creating the child elements, setting their text as well as values to their data attribute same as the value entered by user and then sort them.

  • Step 5 − In the next step, we will define another JavaScript function, which will select all the child element once and then sort them according to the data attribute values with the help of comparator function passed inside the sort() method.

  • Step 6 − In the last step, we will assign the function defined in the previous step as a value to the onclick event of the second button defined in the third step.

Example

The example below explains how you can use the getAttribute() method to get the values of the data attribute of the child elements and sort them according to that value −

<!DOCTYPE html>
<html>
<body>
   <h2>Sort element by numerical value of data attribute using JavaScript</h2>
   <p>Set the data percentage property and the content of each child:</p>
   <input type = "number" id = "inp1" placeholder = "Data Percentage"> <br><br>
   <p id = "prev">The initial order of paragraph elements in the container element is:</p>
   <div id = "container"> </div>
   <button id = "add" onclick = "appendElement()">Append element to the parent element</button>
   <button id = "btn" onclick = "sortParent()">click to sort</button>
   <p id = "result"> </p>
   <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <script>
      var result = $("#result");
      var prev = $("#prev");
      var container = $("#container");
      function appendElement() {
         var inp1 = $("#inp1");
         var val1 = inp1.val();
         var num = Number(val1);
         var paras = $(" <p> </p> ").text(num);
         paras.addClass("childPara");
         paras.attr("data-percentage", num);
         paras.appendTo(container);
         inp1.val("");
      }
      function sortParent() {
         function cmp(x, y) {
            return x.getAttribute("data-percentage") - y.getAttribute("data-percentage");
         }
         var childElements = container.find(".childPara");
         var sortedChildElements = childElements.sort(cmp).appendTo(container);
         prev.html(" <b> The final sorted order of the child elements of the container element is: </b> ");
         result.html(" The elements are sorted finally. ");
      }
   </script>
</body>
</html>

In this example, we have used the getAttribute() method inside the comparator function cmp to compare the values of the data-percentage attribute given to the child elements.

Using the dataset.percentage property

The dataset.percentage property is used to get the value of the data-percentage attribute given to the selected element and then we can use this property to compare the values and sort the elements according to those values.

Syntax

Following syntax is used to get the value of data attributes of the child elements using the dataset.percentage property −

Selected_element.data.percentage;

Let us understand it practically with the help of code example and sort the child elements of an element.

Approach

The appraoch of this example is very similar to the algorithm of the previous example. You just need to replace the getAttribute() method syntax of the cmp function in previous algorithm with the dataset.percentage property syntax to compare the child elements.

Example

Below example will explain you how to use the dataset.percentage property to compare the data attribute values of each child element and sort them −

<!DOCTYPE html>
<html>
<body>
   <h2>Sort element by numerical value of data attribute using JavaScript</h2>
   <p>Set the data percentage property and the content of each child:</p>
   <input type = "number" id = "inp1" placeholder = "Data Percentage"><br><br>
   <p id = "prev"> The initial order of paragraph elements in the container element is:</p>
   <div id = "container"> </div>
   <button id = "add" onclick = "appendElement()">Append element to the parent element</button>
   <button id = "btn" onclick = "sortParent()">click to sort </button>
   <p id = "result"> </p>
   <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <script>
      var result = $("#result");
      var prev = $("#prev");
      var container = $("#container");
      function appendElement() {
         var inp1 = $("#inp1");
         var val1 = inp1.val();
         var num = Number(val1);
         var paras = $(" <p> </p> ").text(num);
         paras.addClass("childPara");
         paras.attr("data-percentage", num);
         paras.appendTo(container);
         inp1.val("");
      }
      function sortParent() {
         function cmp(x, y) {
            return x.dataset.percentage - y.dataset.percentage;
         }
         var childElements = container.find(".childPara");
         var sortedChildElements = childElements.sort(cmp).appendTo(container);
         prev.html(" <b> The final sorted order of the child elements of the container element is: </b> ");
         result.html(" The elements are sorted finally. ");
      }
   </script>
</body>
</html>

In the above example, we have used the dataset.percentage property to get the value of the data-percentage attribute and sort the child elements according to the value of those attributes.

Conclusion

In this article, we have learned about the two different methods of getting the value of the data attrbute and sort them according to the values of those attributes. We have discussed these methods with the help of code examples to implement them practically and sort the child element of a element using these methods.

Updated on: 20-Nov-2023

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements