How to write a simple DOM tree traversal algorithm in jQuery?

I would like to take the code found here: http://www.jslab.dk/articles/non.recursive.preorder.traversal.part2

// HTML element var root = document.documentElement; recursivePreorder(root); // Recusively find and handle all text nodes function recursivePreorder(node) { // If node is a text node if (node.type == 3) { // Do something with node } // else recurse for each child node else { for(var i=0; i<node.childNodes.length; i++) recursivePreorder(node.childNodes[i]); } } 

and convert it to pure jQuery.

Any idea? I know that recursion requires the .callee argument, since jQuery callbacks are anonymous, but I'm too new to jQuery to accept it later on.

Thanks!

+1
source share
4 answers

As Code Duck pointed out, jQuery traverses nodes in the original order, in depth - or, as you call it, pre-order. However, contents only gets nodes for children, not descendants. Try the following:

 $(document).contents ().each (function processNodes () { if (this.nodeType == 3) doSomething (this); // do something with text node else $(this).contents ().each (processNodes); }); 

As a third-party, arguments.callee flagged for deprecation, therefore a named function (as opposed to anonymous)

+8
source

If this is not homework, and you are forced to go through all the crazy frenzy, then, of course, with jQuery the easiest way to accomplish everything that you are trying to do ...

jQuery has a fairly robust set of selectors that allows you to simply select and return a collection of an entire specific type of element within a page or element (for example, all paragraph tags in a given div tag). They will be returned to you in the order in which they appear in the DOM (which is largely related to the above). Alternatively, you can use the filter as shown above.

If you need to do this in a specific order, I would suggest using selectors or filters to grab the element you want to start with and then iterate over its children recursively. jQuery has a built-in function to return the children of this element.

0
source

Like the jQuery plugin: (also adds an interrupt function (e.g. jQuery.each ) and an option for pre-or post-order YMMV followed by order)

 $.fn.walk = function(visit, post_order) { if(this.length === 0) { return; } this.each(function(i) { if (!post_order) { if (visit.call(this, i, this) === false) { return false; } } $j(this).children().walk(visit, post_order); if (post_order) { return visit.call(this, i, this); } }); } 
0
source

I think it's just like

 var collection=$(document).contents().filter(function() { return this.nodeType == 3; }); 

Then you can either run your commands in collection using $.each , or if you want to run the jQuery method in a set, you cannot assign it to a variable and bind the method to the end.

-1
source

All Articles