Moving Unordered Lists Using Javascript / JQuery

Suppose I have an unordered nested list:

<ul> <li>Item a1</li> <li>Item a2</li> <li>Item a3</li> <ul> <li>Item b1</li> <li>Item b2</li> <li>Item b3</li> <ul> <li>Item c1</li> <li>Item c2</li> <li>Item c3</li> </ul> <li>Item b4</li> </ul> <li>Item a4</li> </ul> 

I need to go through it and save it in a two-dimensional array (ultimately, I'm just trying to convert it to a JSON object). I am allowed to use jQuery AND / OR Javascript. How do I proceed?

thanks

+1
source share
3 answers

I'm not sure what you want the resulting data structure to look like, but this (which uses some jQuery):

 $(function() { var result = {}; function createNewLevel(parent,items) { var length = items.length; for(var i = 0; i < length; i++) { if(items[i].tagName == 'UL') { parent['ul' + i] = {}; createNewLevel(parent['ul' + i],$(items[i]).children().get()); } else { parent['li' + i] = $(items[i]).text(); } } } createNewLevel(result, $('ul:first').get()); console.log(result); }); 

... will create this structure

 { ul0: { li0: "Item a1", li1: "Item a2", li2: "Item a3", li4: "Item a4", ul3: { li0: "Item b1", li1: "Item b2", li2: "Item b3", li4: "Item b4", ul3: { li0: "Item c1", li1: "Item c2", li2: "Item c3" } } } } 

It could be fairly easy to customize to change the details of the resulting structure if necessary.

Note that this is a javascript object. If you really need a JSON object, you just need to convert it using var jsonResult = JSON.stringify( result );

+2
source
 function traversing(ul) { for(var index=0;index<ul.childNodes.length;index++){ if(ul.childNodes[index].childNodes.length>0){ traversing(ul.childNodes[index]); } //perform other operation } } 
+2
source

Using jQuery try:

 $.each($("li"), function(index, value) { alert(value); }); 
0
source

All Articles