jQuery.deForm 0.0.0 for jQuery.dForm 1.0.1 example
This is an example to show how jQuery.dForm output (or any DOM structure) can be compiled back into a JSON object... Not production ready.
by Graham Dixon
HTML
<script src="https://rawgit.com/daffl/jquery.dform/master/dist/jquery.dform-1.1.0.js"></script>
<div id="somediv">
<div>
<p> Converting DOM to daffls dForm JSON structure </p>
</div>
<ul id="test-ul-1" class="test">
<li id="test-ul-1-li-1">
<ul id="test-ul-1-li-1-ul-1">
<li id="test-ul-1-li-1-ul-1-li-1" style="background:#CCC;color:#000;"><a>test</a></li>
<li id="test-ul-1-li-1-ul-1-li-2"><a>test</a></li>
<li id="test-ul-1-li-1-ul-1-li-3"><a>test</a></li>
</ul>
</li>
<li id="test-ul-1-li-2">test</li>
<li id="test-ul-1-li-3">test</li>
</ul>
</div>
<div id="putie"> </div>
<div id="myform"> </div>
JavaScript
$.each($('#somediv').children(), function(key) {
//somediv will only have a firstchild.
var clean = $(this).clone().wrap('<div>').parent().html();
var initElement = multilineTrim(clean);
var json = mapDOM(initElement, true);
$('#putie').append(json);
$("#myform").dform(JSON.parse(json));
//and back again.
});
initElement = "<div><span>text</span>Text2</div>";
json = mapDOM(initElement, true);
//console.log(json);
function multilineTrim(htmlString) {
// split the string into an array by line separator
// call $.trim on each line
// filter out the empty lines
// join the array of lines back into a string
var string = htmlString.split("\n").map($.trim).filter(function(line) {
return line != ""
}).join("");
return specialTrim(string);
}
function specialTrim(str) {
//Remove any spaces that distort positioning
return str.replace(/>\s+</g, '><');
}
function mapDOM(element, json) {
var treeObject = {};
// If string convert to document Node
if (typeof element === "string") {
if (window.DOMParser) {
parser = new DOMParser();
docNode = parser.parseFromString(element, "text/xml");
} else // Microsoft strikes again
{
docNode = new ActiveXObject("Microsoft.XMLDOM");
docNode.async = false;
docNode.loadXML(element);
}
element = docNode.firstChild;
}
//Recursively loop through DOM elements and assign properties to object
function treeHTML(element, object) {
object["type"] = element.nodeName;
if (element.attributes != null) {
if (element.attributes.length) {
for (var i = 0; i < element.attributes.length; i++) {
if (element.attributes[i].nodeName === "style") {
var styles = element.attributes[i].nodeValue.split(';');
var newStyle = {};
for (var s =...