4

I have created this jsfiddle: http://jsfiddle.net/mfnxm/1/

I am trying to create this JSON:

[{
"link":"/about",
"title":"About",
"nodes":[{
    "link":"/staff",
    "title":"Staff",
    "nodes":[{
        "link":"/heads",
        "title":"Dept Heads"
        },{
        "link":"/support",
        "title":"Support"
        }]
    },{
    "link":"/location",
    "title":"Location"
    }]
},{
"link":"/contact",
"title":"Contact"
}]

From this unordered list:

<div id="tree">
    <ul class=".sortable">
        <li><a href="/about">About</a>
            <ul class=".sortable">
                <li><a href="/staff">Staff</a>
                    <ul class=".sortable">
                        <li><a href="/heads">Dept Heads</a></li>
                        <li><a href="/support">Support</a></li>
                    </ul>
                </li>
                <li><a href="/location">Location</a></li>
            </ul>
        </li>
        <li><a href="/contact">Contact</a></li>
    </ul>
</div>

Here's the javascript so far (borrowed from here) - but it is not creating the nodes elements for me:

var out = [];
function processOneLi(node) {       
    var aNode = node.children("a:first");
    var retVal = {
        "link": aNode.attr("href"),
        "title": aNode.text()
    };
    node.find("> .sortable > li").each(function() {
        if (!retVal.hasOwnProperty("nodes")) {
            retVal.nodes = [];
        }
        retVal.nodes.push(processOneLi($(this)));
    });
    return retVal;
}
$("#tree ul").children("li").each(function() {
    out.push(processOneLi($(this)));
});

// Do something with data
$('#d').text(JSON.stringify(out));

What am I missing? Thanks!

0

1 Answer 1

2

Replace class=".sortable" in your HTML with class="sortable" (no period) at every occurrence.

You also need to change $("#tree ul").children("li").each(function() to $("#tree > ul > "li").each(function() { to avoid redundant processing.

http://jsfiddle.net/mblase75/mfnxm/2/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.