I have a list of comments, each of which has a vote count (either positive or negative). I’m trying to pull out the top two comments (based on highest net votes, not vote count), copy their HTML, and add them to a new section titled “top ideas”
I want to duplicate the entire for the two comments with the highest number in the
HTML (an over simplified version)… this is repeated for each comment:
<div class="comment">
<div class="thumbblock">
<div class="ratingtext">
<div>
<span class="num-total" data-voteup="8" data-votedown="4">+4</span>
</div><!-- END random div -->
</div><!-- END ratingtext -->
</div><!-- END thumbblock -->
<p>comment text</p>
</div><!-- END comment -->
jQuery:
jQuery(document).ready(function($) {
//number of top comments to show
var showResults = 2;
//loop through each total rating
//only pull the top two (in this case)
$('span.num-total').slice(0, showResults).each(function(index){
//calculate the net vote total based on data-voteup and data-votedown
var upVotes = $(this).data('voteup');
var downVotes = $(this).data('votedown');
var netVotes = upVotes - downVotes;
//get the HTML for those comments
var commentHTML = $(this).parents('.comment').html();
//append that HTML to the top comment div
$('div.top-comments').append('<div class="comment">' + commentHTML + '</div>');
});
});
See the live copy here: http://jobelty.com/company/apple
The jQuery is coming from a file called top-comments.js
You’re cutting the list down before sorting, so at best you’ll get the text of whichever two comments happen to be at the top.
A version that grabs the full comment elements of the two highest-ranked comments, and copies those into
.top-comments
:From what I can tell you have everything working except for the part where you determine what the top two comments are. Here’s an approach based on sorting the comment elements first. Code is untested:
Try
Demo: Fiddle