jQuery – Wrap children div with Page Number and Index

jQuery can be used to modify the html before it is rendered in the browser. In the following example, i will wrap those children div with page number and index. Then we can apply css on those newly created div for better layout.

<html>
	<head>
		<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
	</head>
	<body>
		<div id="all-options">
			<div>Adam</div>
			<div>Anna</div>
			<div>Apple</div>
			<div>Banana</div>
			<div>Bob</div>
			<div>Bobby</div>
			<div>Bonny</div>
			<div>Book</div>
			<div>Cat</div>
			<div>Cathy</div>
			<div>Dog</div>
			<div>Dickson</div>
			<div>Dirty</div>
			<div>Doom</div>
			<div>Draw</div>
			<div>Egg</div>
			<div>Food</div>
			<div>Girl</div>
			<div>Hera</div>
			<div>Hero</div>
			<div>Horse</div>
			<div>Ice</div>
			<div>Ivy</div>
			<div>Jumbo</div>
			<div>Kennedy</div>
			<div>Kent</div>
			<div>Kitty</div>
			<div>Lemon</div>
			<div>Man</div>
			<div>Manchester City</div>
			<div>Mansfield</div>
		</div>
		
		<script>
		  var max_count = 4;
		  var count = 1;
		  var index = 1;
			var total = $('#all-options div').size();
			var total_div_inserted = ($('#all-options div').size() / max_count) + 1;
			var current_alphabet;
			var last_alphabet = '*';
			
			// insert the page div first
			for (i = 1; i <= total_div_inserted; i++) {
				var new_div = "<div class='page-"+i+"'></div>";
				$('#all-options').before(new_div);
				
				// move the options to the corresponding page div
				for (j = 1; j <= max_count; j++) {
					$('#all-options div:first-child').appendTo($('div.page-'+i));
					
					// add index class to the page div
					current_alphabet = $('div.page-'+i+' div:last-child').text().substring(0,1);
					if (current_alphabet != last_alphabet) {
						$('div.page-'+i).addClass('index-'+current_alphabet);
					}
					last_alphabet = current_alphabet;
				}
			}
		
			// move all pages div back to all-options
			for (i = 1; i <= total_div_inserted; i++) {
				$('div.page-'+i).appendTo($('div#all-options'));
			}
		</script>
	</body>
</html>

 

If we view the page in browser, seems there is nothing changed. but when you view the source through firebug, you will find the new div with page number and index.

 

Done =)

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.