Skip to content Skip to sidebar Skip to footer

Using Js To Wrap Pairs Of
  • In Divs
  • It seems like I need some pretty basic JS help. I an trying to make a script that will add a
    around every two listelements in a
      . The amount of list elements

    Solution 1:

    using jquery you can try:

                $(document).ready(function(){               
                    var lis = $("li");
                    for(var i = 0; i < lis.length; i+=2) {
                        lis.slice(i, i+2).wrapAll("<div></div>");
                    }
                });
    

    Solution 2:

    Instead of wrapping in extra non-semantic elements, try using the CSS :even and :odd classes instead. More info found at: Using CSS :even and :odd pseudo-classes with list items

    Solution 3:

    This gives the desired output:

    <html><head><scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"type="text/javascript"></script><scripttype="text/javascript">jQuery(document).ready(function(){ 
            var str="",fHtml="";
            var i=0;
            $("li").each(function(key,val){
                str+="<li>"+$(this).html()+"</li>";
                if(++i==2) { 
                        i=0;    
                        fHtml+="<div>"+str+"</div>";
                        str=""; 
                    }
             });
             $("ul").html(fHtml)
        });
        </script></head><body><ul><li>first Div</li><li>first Div</li><li>second div</li><li>second div</li><li>third div</li><li>third div</li></ul></body></html>

    Solution 4:

    If you just want to show that list of elements in pairs of two next to eachother, independent of their size, you can just use CSS3:

    Define float:left for all li elements, and then use the :nth-child(odd) selector to add clear: left; for all odd li elements (1st, 3rd, 5th, etc)

    in action: http://jsfiddle.net/e63Rv/

    Post a Comment for "Using Js To Wrap Pairs Of
  • In Divs"