Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery append() not adding </ul><ul> [duplicate]

Possible Duplicate:
Using .after() to add html closing and open tags

I want to show 3 columns lists (<ul>) with almost the same height, so I'm counting the <li> tags and use append to generate the list dynamically. But when I do $el.append($("</ul><ul class='new'>")) to close the current list and append a new one it appends like <ul class='new'></ul>.

I just want to close the <ul> tag and open it again. Is jQuery append() function validating somehow the DOM structure? How can I get the spected result? Any better way to achieve this?

HTML:

<div id="mylist">
   here the list will show
</div>

Jquery:

var $el = $("#mylist");
$el.empty(); // remove old options
$el.append($("<ul class='new'>"));
var j = parseInt(response.length/3);
var i = 0;
$.each(response, function(key, value) {
  i++;
  if(i%j==0){
      $el.append($("</ul><ul class='new'>")).append($("<li></li>").text(value.nombre));
  }
  else{
     $el.append($("<li></li>").text(value.name));
  }});

Expected result:

<div >
   <ul class="new">
     <li>Lorem Ipsum</li>
     <li>Lorem Ipsum</li>
     <li>Lorem Ipsum</li>
   </ul><ul class="new"> //This is what I want to append
     <li>Lorem Ipsum</li>
     <li>Lorem Ipsum</li>
     <li>Lorem Ipsum</li>
   </ul><ul class="new">
     <li>Lorem Ipsum</li>
     <li>Lorem Ipsum</li>
   </ul>
</div>

What I got:

<div id="mylist">
<ul class="new"></ul>
 <li>Lorem Ipsum</li>
 <li>Lorem Ipsum</li>
 <li>Lorem Ipsum</li>
 <ul class="new"></ul>
 <li>Lorem Ipsum</li>
 <li>Lorem Ipsum</li>
 <li>Lorem Ipsum</li>
 <ul class="new"></ul> 
 <li>Lorem Ipsum</li>
 <li>Lorem Ipsum</li>
</div>
like image 872
Tom Sarduy Avatar asked Dec 16 '22 14:12

Tom Sarduy


1 Answers

Simple:

LIVE DEMO

Instead of objects, play with "strings" to set </ul><ul> where needed.

var arr = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14'];

var str = "<ul class='new'>";
for(var i=0; i<arr.length;) { 
              str += "<li>"+ arr[i++] +"</li>" ;  
  if(i%3===0) str += "</ul><ul class='new'>"   ;
}
str += "</ul>" ;

$("#mylist").html( str );
like image 167
Roko C. Buljan Avatar answered Dec 28 '22 09:12

Roko C. Buljan