Question

I have a variable in which i search for ul's. I want every ul to split into 2 equal ul's and replace the original ul with these 2 new ul's.

I can't do this with CSS, because i want the li's to display from top to bottom every column, instead of from left to right.

I have the following code, but I am stuck right now...

<script type="text/javascript">
var wid_tekst1 = "<?php echo $wid_tekst1; ?>";
$(wid_tekst1).filter('ul').each(function() {

    //Create array of all posts in lists
    var postsArr = new Array();
    $postsList = $(this);

    $(this).find('li').each(function(){
        postsArr.push($(this).html());
    })

    //Split the array at this point. The original array is altered.
    var firstList = postsArr.splice(0, Math.round(postsArr.length / 2)),
    secondList = postsArr,
    ListHTML = '';
    function createHTML(list){
        ListHTML = '';
        for (var i = 0; i < list.length; i++) {
            ListHTML += '<li>' + list[i] + '</li>'
        };

    }

    //$(firstList).before('<ul>');
    //$(firstList).after('</ul>');

    //$(secondList).before('<ul>');
    //$(secondList).after('</ul>');

    alert(firstList);
    alert(secondList);

})
</script>

Thanks for your help...

UPDATE:

I now have the following:

<script type="text/javascript">
$( document ).ready(function() {
var wid_tekst1 = $('.content');

$(wid_tekst1).filter('ul').each(function() {
    var $li = $(this).children(),
        $newUl = $('<ul>').insertAfter(this),
        middle = Math.ceil($li.length / 2) - 1;
    $li.filter(':gt(' + middle + ')').appendTo($newUl);

    //alert($newUl); 
});
});
</script>

It doesn't split the ul's into 2. The only way I got it working was by setting

var wid_tekst1 = "*";

But if I set variable wid_tekst1 to all, it replaces all ul's in the webpage. I only want to replace the ul's within the .content-class

Thank you

Was it helpful?

Solution

Your code can be optimized:

$(wid_tekst1).filter('ul').each(function() {
    var $li = $(this).children(),
        $newUl = $('<ul>').insertAfter(this),
        middle = Math.ceil($li.length / 2) - 1;
    $li.filter(':gt(' + middle + ')').appendTo($newUl);    
});

Demo: http://jsfiddle.net/R3VYZ/

Messing with innerHTML (when you construct lists using strings) is not ideal, since you will lose all event original handlers if there were something bound.

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