Stepped DOM traversal

G

guy001

Hi, I'm trying to traverse the DOM in a bit of a non-traditional manner
and am struggling to get my head around it.

Just say i have some elements like so:

A
|-B
|-C
| |-D
|
|-E

Typically, when the DOM is traversed you would get the following order:
ABCDE

What I would like to do is step through one level at a time like so:
A|BCE|D

Any pointers would be greatly appreciated!
 
L

Lasse Reichstein Nielsen

Hi, I'm trying to traverse the DOM in a bit of a non-traditional manner
and am struggling to get my head around it.

It's called /breadth-first/ traversal.
What you call the traditional way is a /depth-first/ traversal)

In computer science, the way to create a breadth-first traversal is
to use a queue to hold the elements to traverse.

---
function traverseDOM(node, action) {
var queue = [node];
while (queue.length > 0) {
var elem = queue.shift();

action(elem);

for (var child=elem.firstChild; child != null; child=child.nextSibling) {
queue.push(child);
}
}
}
---

(A depth first traversal uses a stack instead of a queue, but since
recursive calls have an implicit stack in the calls, it can also be
implemented using a simple recursive descent).

See <URL:http://mathworld.wolfram.com/Breadth-FirstTraversal.html>

Good luck
/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top