NestedList2JSON

by michaelschmid

HTML

<ul id="tasks">
    <li id="">
      Task1
      <ul>
        <li id="taskli">Task2</li>
      </ul>
    </li>
    <li>Task3</li>
    <li>Task4</li>
</ul>

<div id="json"> 
</div>

JavaScript

// Get the parent element somehow, you can just as well use
// .getElementById() or any other DOM method
var parentElement = document.querySelector('#taskli');
// Returns the text content as a string
console.log ([].reduce.call(parentElement.childNodes, function(a, b) { return a + (b.nodeType === 3 ? b.textContent : ''); }, ''));


function getLi(elem) {

	// https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/
  
    var lis = elem.querySelectorAll('li');

    [].forEach.call(lis, function(li) {
      // do whatever
      console.log(li);
    });

	/*
		return [].map.call(elem.querySelectorAll("li"), function(o) {
			// recursive call
      // var subs = getLi(o.querySelectorAll(":scope > li"));
      
			var li = { "Name" : o.textContent.replace(/\s/g, ""),
								"Tasks": getLi(o)
							};
			return li;
		});
    */
};

document.querySelector('#json').textContent = JSON.stringify(getLi(document.querySelector('#tasks')));