The following code will:
- split columns by dividing the number of elements in half then it will
-create a new div and add the remaining content to the new div
Below I am trying to do this using “each()” and it -mostly- works except it is adding the new div .second the the first instance of #container -although it IS reading each group and splitting correctly.
jQuery:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script>
$(document).ready(function(){
$('body > #container').each(function(){
var select = $(this);
//var chooseme= select.find('#container');
var count= select.find('div.firstcol > div.datarow').length;
if (count>1)
{
if (count & 1)
{
$("<div></div>").attr('class','secondcol').appendTo('#container');
$('div.firstcol > div.datarow').eq(count/2).nextAll().appendTo('.secondcol');
}
else
{
$("<div></div>").attr('class','secondcol').appendTo('#container');
$('div.firstcol > div.datarow').eq(count/2-1).nextAll().appendTo('.secondcol');
}
} //if
});//each
});//ready
</script>
HTML:
<style>
body{font-family:arial;}
.firstcol{float:left;padding-left:100px;background-color:#ccc}
.secondcol{float:left;color:blue;position:relative;padding-left:100px;}
.secondcol h3 {font-size:18px;font-weight:normal;color:grey}
span{}
</style>
</head>
<body>
<div id="container">
<div class="firstcol">
<div class="datarow">
<span class="label">File Type</span>
<span class="value">JPG File</span>
</div>
<div class="datarow">
<span class="label">File Type</span>
<span class="value">JPG File</span>
</div>
<div class="datarow">
<span class="label">File Type</span>
<span class="value">JPG File</span>
</div>
</div>
</div>
<!--**********second group****************-->
<div id="container">
<div class="firstcol">
<div class="datarow">
<span class="label">File Type</span>
<span class="value">JPG File</span>
</div>
<div class="datarow">
<span class="label">File Type</span>
<span class="value">JPG File</span>
</div>
</div>
</div>
After: as the code renders this will result:
<body>
<div id="container">
<div class="firstcol">
<div class="datarow">
</div>
<div class="secondcol">
**<div class="secondcol">**
</div>
<div id="container">
<div class="firstcol">
<div class="datarow">
<div class="datarow">
</div>
</div>
The problem is I want that secondcol to go into the second container
You can’t give two HTML nodes the same ID. IDs are supposed to be unique! 🙂 Try changing the ID to the second instance of the
containerto something else, update this in your javascript as well (appendTo('#container2')) and see what happens