LP elements into LPT

by sanford

HTML

<div class="lpeCElement src1">
    <i>This was originally inside src1.</i>
</div>
<div class="lpeCElement src2">
    <div>This
        <div>was
            <div>originally
                <div>inside
                    <div>src2.</div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="lpeCElement src3">
    <img src="/favicon.png">
    <div>This was originally inside src3.</div>
</div>
<div data-content-from=".src1"></div>
<div data-content-from=".src2"></div>
<div data-content-from=".src3"></div>
<!-- in this demo, there is no element matching '.src4', in order to show the error msg -->
<div data-content-from=".src4"></div>

CSS

BODY {
    padding: 20px;
    font: 11px/11px Verdana;
}
.lpeCElement {
    /* in production, you would simply set display: none to hide the empty templates */
    opacity: .5;
    border: 1px solid silver;
    padding: 20px;
    width: 50%;
    margin:2px;
}
.lpeCElement:after {
    content:"This container has class '" attr(class)"'.";
    color: black;
    font: 11px/11px monospace;
    display:block;
    margin-top: 10px;
}
[data-content-from] {
    border: 1px solid goldenrod;
    padding: 20px;
    width: 50%;
    margin:2px;
}
[data-content-missing]:after {
    content:"If you see this text, a template w/selector " attr(data-content-from)" was not found in the document.";
    color: orangered;
    font: 11px/11px monospace;
}
HTML[id^="ext4"] [data-content-missing]:after {
    content:"Replaced with content of selector " attr(data-content-from) ".";
    color: gray;
}

JavaScript

(function fillTemplatesWithContent() {
    Array.prototype.forEach.call(document.querySelectorAll('[data-content-from]'), function (templateEl) {
        // find content container from selector string
        var contentSelector = templateEl.getAttribute('data-content-from'),
            contentEl = document.querySelector(contentSelector);

        // move child nodes from content --> template or flag error on missing content
        if (contentEl) {
            while (contentEl.hasChildNodes()) {
                templateEl.appendChild(contentEl.firstChild);
            }
        } else {
            templateEl.setAttribute('data-content-missing', 'true');
        }

    });
})();