bbruman bbruman - 2 months ago 11
Javascript Question

Append List Element Multiple Times based off Variable

Here's what I have so far

var count_element = $('div.wp-playlist-item > li').length;
totalcount = 10 - count_element;
if ( totalcount > 1 ) {
$('div.wp-playlist-item').append('<li class="wp-playlist-caption"><div title="" data-original-title="" data-toggle="tooltip" data-title="0:00" data-placement="left" class="next-songs"><span class="wp-playlist-item-title">Blank</span></div></li>');
}


Basically I am trying to make it so that
div.wp-playlist-item
always has 10 list elements.

So, unless
totalcount
= 0 (10 - 10), append this list element.

In my current test environment,
totalcount
is equal to 8, so we want to fire our append command 8 times.

My current code works properly only to fire the proper append once.

Answer
var count_element = $('div.wp-playlist-item > li').length;
totalcount = 10 - count_element;
if ( totalcount > 1 ) {
  for (var i=0; i< totalcount; i++) {
     $('div.wp-playlist-item').append('<li class="wp-playlist-caption"><div title="" data-original-title="" data-toggle="tooltip" data-title="0:00" data-placement="left" class="next-songs"><span class="wp-playlist-item-title">Blank</span></div></li>');
   }
 }

Demo https://jsbin.com/qanoput/edit?html,js,output

Try this once loop and append.