How to sort HTML elements by data-attribute?


In this article, we are going to learn about the ways of sorting the child elements of an element in the HTML document with the help of data attribute. The are many data attribute available in HTML to use. We can sort the elements by using any of those data attributes. In this article, we will sort the elements with the help of two different data attributes, where one will sort the elements according to the length of the value given to it and another will sort according to the numerical values. The data attributes are listed below −

  • Using data-index attribute.

  • Using data-subject attribute.

Let us discuss practical implementation of both the data attributes written above in details with the help of code examples.

Using data-index attribute

The data-index attribute is an attribute that takes the values in the numerical form and it will help us to sort the elements in the order we want to sort them according to the numerical values given to this attribute.

Syntax

Following syntax will show you how you can use the data-index attribute with any HTML element −

<div data-index = " numeric_value "> content of the element </div>

Let us now understand how we can use the data-index attribute to sort the elements practically with the help of code example.

Steps

  • Step 1 − In the first step, we will add an input element of number type to the HTML document to get the numerical input number from user and assign this entered value as value to data-index attribute and text of the newly created element.

  • Step 2 − In this step, we will add a container element to which we will append the child elements dynamically and then sort them with numeric values of their data-index attribute.

  • Step 3 − In the next step, we will add two different button elements with onclick events associated with them, where the first button will add the child element to the container defined in the last step and the second button will sort the child elements and display the result on the user screen.

  • Step 4 − In the fourth step, a JavaScript function will be declared which contains the logic of adding the child element to the container element and assign it to the onclick event of the first button added in the previous step.

  • Step 5 − In the last step, we will define another JavaScript function and assign it to the onclick event of the second button defined in the third step. This function will sort the elements according to the numerical values of the data-index attribute.

Example

The example below will illustrates how we can sort the elements with the help of data attribute according to the numerical values −

<!DOCTYPE html>
<html>
<body>
   <h2>Sort element by numerical value of data attribute using JavaScript</h2>
   <p>Enter any number of your choice:</p>
   <input type = "number" id = "inp1" placeholder = "Numeric Value"><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 = "setValues()">Append element to the parent element</button>
   <button id = "btn" onclick = "sortElement()">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 setValues() {
         var inp1 = $("#inp1");
         var val1 = inp1.val();
         var num = Number(val1);
         var paras = $(" <p> </p> ").text(num);
         paras.addClass("childPara");
         paras.attr("data-index", num);
         paras.appendTo(container);
         inp1.val("");
      }
      function sortElement() {
         function cmp(x, y) {
            if (x.dataset.index > y.dataset.index)
               return 1;
            if (x.dataset.index < y.dataset.index)
               return -1;
            return 0;
         }
         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 data-index attribute and sort the elements according to the numerical values stored in the data-index attribute of each element.

Using data-subject attribute

The data-subject attribute is an attribute that takes the values in the form of string values and we can compare the length of those string values in the comparator function to sort the elements according to the length of the value stored in data attribute.

Syntax

Following syntax will show you how to use the data-subject attribute with any element in the HTML document −

<div data-subject = " string_value "> content of the element </div>

Let us now discuss its practical implementation in details by implementing it inside a code example.

Algorithm

The algorithm of the previous example and this example is almost similar you just need to perform the following changes to sort the elements by length of the value given to data-subject attribute −

  • Add two input elements of text type.

  • Compare the dataset.subject.length of two parameters of comparator function instead of dataset.index.

By performing above changes you are good to go for sorting the elements according to the string values.

Example

Below example will explain the above changes in the previous algorithm and help you to use the data-subject to sort elements according to the length of the value given to it −

<!DOCTYPE html>
<html>
<body>
   <h2>Sort HTML elements by data-attribute</h2>
   <p>Enter your subject Name and any topic of that subject:</p>
   <input type = "text" id = "inp1" placeholder = "Subject Name"><br><br>
   <input type = "text" id = "inp2" placeholder = "Topic Name"><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 = "setValues()">Append element to the parent element</button>
   <button id = "btn" onclick = "sortElement()">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 setValues() {
         var inp1 = $("#inp1");
         var val1 = inp1.val();
         var text1 = val1;
         var inp2 = $("#inp2");
         var val2 = inp2.val();
         var text2 = val2;
         var paras = $(" <p> </p> ").text(text1 + " : " + text2);
         paras.addClass("childPara");
         paras.attr("data-subject", text1);
         paras.appendTo(container);
         inp1.val("");
         inp2.val("");
      }
      function sortElement() {
         function cmp(x, y) {
            if (x.dataset.subject.length < y.dataset.subject.length)
               return -1;
            if (x.dataset.subject.length > y.dataset.subject.length)
               return 1;
            return 0;
         }
         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 data-subject attribute to sort the elements according to the length of the values store in them.

NOTE − In both of the above examples, if you exchange the values that are compared with each other in the comparator function, then it will sort the elements in the opposite order, such that decreasing order of the numerical values in first example and decreasing order of the string length in the second example.

Conclusion

In this article, we have discussed the methods of sorting the elements with the help of data attributes and see two different examples of sorting where we sort the elements in numerical as well as string length order.

Updated on: 20-Nov-2023

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements