Iterate through HTML DOM and get depth

How is it possible to iterate through the HTML DOM and list all nodes with there depth in javascript. Example: <div> <img src="foo.jpg"> <p> <span>bar</...