How to iterate through a DOM tree?

I'm working on a website which uses a tree structure made the following way : a list is created and if an element of this list is itself a list then it is append to the first list using appendChild. The big list is put in a div named 'tree'. I would like to access the content of the div 'tree' and go through the nodes to display them.

I've tried to code it several ways but it doesn't work, does someone has any idea how to do it ?

Edit (my code was too long)



This function iterates through a DOM tree. You can pass it a callback that takes the parent and child element too:

_SU3.treeIterate = function(parent, callback) {
   var children = _SU3.getChildren(parent);
   for (var i = 0; i < children.length; i++) {
      var child = children[i];
      callback(parent, child);
      _SU3.treeIterate(child, callback);

_SU3.getChildren = function(parent) {

  var children = new Array();

  var childNodes = parent.childNodes;
  if (childNodes == null) 
    return children;

  for (var i = 0; i < childNodes.length; i++) {
     var child = childNodes[i];
     if (child.tagName == "li" || child.tagName == "LI") {
  return children;

Note: in this example the getChildren() function only finds "li" items. Amend as necessary.


If you think you will need several other functions on the tree, I suggest you to have a look on jsTree


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.