tbeseda
3/20/2009 - 3:54 PM

gistfile1.htm

<!-- The code I'm stuck with -->
<ul>
	<li class="level1">textytext</li>
		<li class="level2">2textytext</li>
		<li class="level2">2textytext</li>
	<li class="level1">textytext</li>
	<li class="level1">textytext</li>
		<li class="level2">2textytext</li>
			<li class="level3">3textytext</li>
			<li class="level3">3textytext</li>
		<li class="level2">2text</li>
	<li class="level1">textytext</li>
</ul>
<!-- My attempt moves the last .level2 li up with the others -->
<script type="text/javascript">
    $(document).ready(function() {  
        $(".level2").wrapAll("<ul class=level2></ul>");
    });  
</script>
<!-- How I want it to look -->
<ul>
	<li class="level1">textytext</li>
		<ul>
		<li class="level2">2textytext</li>
		<li class="level2">2textytext</li>
		</ul>
	<li class="level1">textytext</li>
	<li class="level1">textytext</li>
		<ul>
		<li class="level2">2textytext</li>
			<ul>
			<li class="level3">3textytext</li>
			<li class="level3">3textytext</li>
			</ul>
		<li class="level2">2text</li>
		</ul>
	<li class="level1">textytext</li>
</ul>

<!-- SUGGESTION FROM zidoh IN #jquery -->
<script>
var curlvl = 1;
var tmp = '';
function get_level($element) {
	return $element.attr("class").charAt(5);
}
$(document).ready(function () {
	$lis = $("#heh").children();
	$lis.each(function () {
		var lvl = get_level($(this));
		if (lvl != 1) {
			if (lvl > curlvl) {
				tmp += '<ul>';
			}
			else if (lvl < curlvl) {
				tmp += '</ul>';
			}
			tmp += '<li class="'+$(this).attr("class")+'">'+$(this).html()+'</li>\n';
			$(this).remove();
		}
		else {
			if (curlvl > lvl) {
				$(tmp).insertBefore($(this));
				tmp = '';
			}
		}
		curlvl = lvl;
	});
});
</script>