mistery_girl mistery_girl - 3 months ago 15
Javascript Question

How to find span with biggest data-item using jQuery

I have a div with spans inside. They have

data-item attr
. How to find div with the biggest
data-item
attr. They are numbers starting from 0. For example I have:



<div class="wrapper">
<span data-num="0">text</span>
<span data-num="1">text</span>
<span data-num="2">text</span>
<span data-num="3">text</span>
</div>





Updated: This is part of my code, it's about uploading files and one of the input fields is multiple. And I show in a div with separate spans image names of the files. Use should add multiple files so I need to find the biggest
data-num
and increment it for the next file.



function getFiles(document, window, index) {
var inputs = document.querySelectorAll( '.app-file' );
input.addEventListener( 'change', function( e )
{
var fileName = '';
var num = 0;

if( this.files && this.files.length > 1 || $(this).next().next().html()) {
var fileName = [];

for (var i = 0; i < this.files.length; ++i) {
fileName.push(this.files.item(i).name);
var comma = '';
if($(this).next().next().html()) {
comma = ',';
}

divName.innerHTML = divName.innerHTML + comma + '<span class="image_name" data-num="'+num+'">' + this.files.item(i).name + '</span><span class="glyphicon glyphicon-remove remove-file" data-toggle="tooltip" data-placement="top" title="Remove"></span>';
num++;
}
} else {
fileName = e.target.value.split('\\').pop();
divName.innerHTML = '<span class="image_wrapper"><span class="image_name" data-num="'+num+'">' +fileName + '</span><span class="glyphicon glyphicon-remove remove-file" data-toggle="tooltip" data-placement="top" title="Remove"></span></span>';
var maxIndexItem = $.makeArray($('#wrapper [data-num]')).reduce(function(result, item) {
return $(item).data('num') > $(result).data('num') ? $(item) : result;
});
alert(maxIndexItem.text());
}
});







}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="file-name" data-input="corporate_document" id="corporates"></div>




Answer

HTML

<div class="wrapper">
  <span data-num="0">text1</span>
  <span data-num="1">text2</span>
  <span data-num="2">text3</span>
  <span data-num="3">text4</span>
  <span>text5</span>
  <span data-num="">text6</span>
</div>

JS

$(document).ready(function(){
    var arr = [];
        $(".wrapper span").each(function(){
        var dataNum = $(this).data("num");
        if (dataNum != null) {
            arr.push(dataNum);
        }
    }).promise().done( function(){
      var max = Math.max.apply(Math, arr);
     alert( $(".wrapper").find("[data-num=" + max + "]").text());
    } );
});

Refer Fiddle

Comments