How to get max attribute value in JQuery?

In this example explain how to get max attribute value in jquery. Let’s discuss about jquery get custom attribute value by class. I would like to show you jquery find max attribute value. I will explain find maximum value of attribute jquery.

Sometimes, you have a many tag and with same class and attribute with value, you need to find maximum value of attribute from that comman class.

How to get max attribute value from same html class using jquery

Now, you require to get max value, I mean you need to 10, because that is big value from other,  so you can get maximum value from this method.

Example 1:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>
<body>
     <ul>
        <li class="testing1" data-id="5">Hello users</li>
        <li class="testing1" data-id="10">Ok</li>
        <li class="testing1" data-id="2">Fine</li>
       
     </ul>
     <script type="text/javascript">

        var maxValue = 0;

        $('.testing').each(function() {
            var value = parseInt($(this).data('id'));
            maxValue = (value > maxValue) ? value : maxValue;
        });
        console.log(maxValue);
     </script>
</body>
</html>
Example 2: How to get max attribute value in jquery using Max method

Let’s show second example how to get max attribute value in jquery. we have list of <div> elements, each with a custome data-item attribute. We want to find maximum data-item value.

<div data-value="5">1</div>
<div data-value="10">2</div>
<div data-value="4">3</div>
JQuery code
$(document).ready(function() {
     var maxValue= Math.max.apply(null, $('div').map(function(){
         return $(this).data('value');
     }).get());
     
     console.log(maxValue);
});

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *