JSFiddle - React, Tailwind, and code Playground

by Serge Zahharenko

HTML

<h1>Case to solve:</h1>
<div id="source">
    Lorem Ipsum is simply dummy text!<br/>
    <span>Bla bla bla</span><br/>
    It is a long established fact that a reader will be distracted by the readable content  <br/>
    <span>Anohter tag!</span><br/>
</div>
<div id="part1"></div>
<div id="part2"></div>
<hr/>
<h1>Simple case:</h1>
<div id="source2">
    <span>Lorem Ipsum is simply dummy text!</span><br/>
    <span>Bla bla bla</span><br/>
    <span>It is a long established fact that a reader will be distracted by the readable content</span><br/>
    <span>Anohter tag!</span><br/>
</div>
<div id="part3"></div>
<div id="part4"></div>

CSS

div {float:left;width:140px;height:140px;border:solid 1px #ccc;margin:20px;overflow:auto;}
h1, hr {clear:both;}
span.red {color:red;}

JavaScript

$(document).ready(function(){
    parseElement('#source', ['#part1','#part2']); 
    parseElement('#source2', ['#part3','#part4']);
})
var ii = 0;
function parseElement(selector,parts, cycle) {
    ii++;
    var cc = $(selector);
    
    var content = cc.contents(),
        total = content.length,
        maxHeight = cc.height(),
        spaceLeft = maxHeight,
        cycle = cycle || 0;
    
    function addToPage(elem,elemSize) {
        elem.appendTo(parts[cycle]);
        spaceLeft -= elemSize;
    }
    function startNewPage() {
        cycle++
        parseElement(selector,parts, cycle);
    }
    $.each(content,function(index,v){
        var elem,
            id = createId();
        if (this.nodeType !== 3) {
            elem = $(this);
        } else {
            $(this).wrap('<span class="red" id="'+id+'"/>');
            elem = $('#'+id);
        }
        var elemSize = elem.outerHeight(true);
        if (elemSize <= spaceLeft) {
            addToPage(elem,elemSize);
        } else if (elemSize > spaceLeft) {
            startNewPage();
        }
    })
}

function createId(){var id=new Date();id='id'+id.getTime()+'r'+Math.floor(Math.random()*(1000+1));return id;}