How do you append a div to the div with the highest data attribute data-number?
$( ".item" ).append( $( "<div class='highest'></div>" ) );
<div id="container">
<div class="item" data-number="13"></div>
<div class="item" data-number="22"></div>
<div class="item" data-number="142"></div>
<div class="item" data-number="2"></div>
<div class="item" data-number="44"></div>
</div>
How do you append a div to the div with the highest data attribute data-number?
$( ".item" ).append( $( "<div class='highest'></div>" ) );
<div id="container">
<div class="item" data-number="13"></div>
<div class="item" data-number="22"></div>
<div class="item" data-number="142"></div>
<div class="item" data-number="2"></div>
<div class="item" data-number="44"></div>
</div>
Share
Improve this question
edited Nov 22, 2014 at 11:52
coder
asked Nov 22, 2014 at 11:36
codercoder
3014 silver badges18 bronze badges
3
-
1
By looping through all of the divs and testing the
data-number
to get the index of the highest one, then append to that one? – nnnnnn Commented Nov 22, 2014 at 11:37 - 2 Are these attributes value unique? What behaviour do you expect if maximum is equal to other one(s)? – A. Wolff Commented Nov 22, 2014 at 11:40
- There can be duplicates, in that case all of them should have the div appended – coder Commented Nov 22, 2014 at 11:43
2 Answers
Reset to default 11demo
var num = $(".item").map(function() {
return $(this).data('number');
}).get();//get all data values in an array
var highest = Math.max.apply(Math, num);//find the highest value from them
$('.item').filter(function(){
return $(this).data('number') == highest;//return the highest div
}).append( $( "<div class='highest'></div>" ));//append to that div
If there can be duplicates then I'd say the simplest method is to loop through the divs twice. The first time you figure out what the highest data-number
is, and then the second time you append to any that have that number:
var highestNum = -1;
$("#container .item").each(function(){
var num = +this.getAttribute("data-number") ;
if (num > highestNum)
highestNum = num;
}).each(function(){
if (highestNum === +this.getAttribute("data-number") )
$(this).append("<div class='highest'></div>");
});
Demo: http://jsfiddle/358njnnx/1/