Traverse a nested list with Javascript/jQuery and store in array

后端 未结 1 1951
-上瘾入骨i
-上瘾入骨i 2021-01-16 10:28

I\'ve seen several questions about converting an array/object into a nested list, but I\'ve found only one relevant question to my issue. I\'ve tried a few ways of accessing

相关标签:
1条回答
  • 2021-01-16 11:04

    I've modified your original code. This should work for all combinations of nested lists. Instead of using children().get(), I used the native JS child methods. It will traverse everything in the list, but ignore elements unless they are <li> or <ul>. Good luck.

                var count = 0;
                var pages = [];
                var parentStack = [];
    
                var result = {};
    
                parentStack.push(0);
    
                function createNewLevel(obj) {
                    var obj = obj || document.getElementById('sortableSitemap');
    
                    if (obj.tagName == 'LI') {
                        ++count;
                        pages.push({
                            pId: parentStack[parentStack.length - 1],
                            urlStr: obj.id, myId: count
                        });
                    }
    
                    if (obj.hasChildNodes()) {
                        var child = obj.firstChild;
                        while (child) {
                            if (child.nodeType === 1) {
    
                                if (child.tagName == 'UL') {
                                    parentStack.push(count);
                                }
    
                                createNewLevel(child);
    
                                if (child.tagName == 'UL') {
                                    parentStack.pop();
                                }
                            }
                            child = child.nextSibling;
                        }
                    }
                }
    
                createNewLevel();
    
    0 讨论(0)
提交回复
热议问题