Question

I'm using jQuery; I need to be able to append multiple LI's based on a data attribute. My html looks like this:

<div class="col">
     <ul class="wonda" data-tick="2"></ul>
     <ul class="panary" data-tick="5"></ul>
</div>

<div class="col">
     <ul class="wonda" data-tick="3"></ul>
     <ul class="panary" data-tick="4"></ul>
</div>

After the script runs it would spit out HTML that looks like this:

<div class="col">
     <ul class="wonda" data-tick="2">
          <li></li>
          <li></li>
     </ul>
     <ul class="panary" data-tick="3">
          <li></li>
          <li></li>
          <li></li>
     </ul>
</div>

<div class="col">
     <ul class="wonda" data-tick="1">
          <li></li>
     </ul>
     <ul class="panary" data-tick="2">
          <li></li>
          <li></li>
     </ul>
</div>

I've tried using append with the data attribute but am getting nowhere. Is there a better way to do this or does anyone have any ideas?

Was it helpful?

Solution

Something like this will work just get the attr data-tick and do a loop creating the elements

 $("ul").each(function(){
      var li = parseInt($(this).attr("data-tick"))
      for(i = 0; i < li; i++){
        //Create an li and append it to this = ul element
        $("<li/>").appendTo(this)
       }
   })

Fiddle

OTHER TIPS

Something like this should work, without need to modify your HTML:

function appendToUl(){
    $('.col').find('ul').each(function(){
        var $self = $(this),
            len = $self.data('tick'); // no need to parseInt, .data() autocasts

        for(var i = 0; i < len; i++){
            $self.empty().append('<li/>');
        }
    });
}

Then you call the function when you need to. The .empty() piece is if you want to call the function multiple times as like a reset function ... if you only call it once, you can remove it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top