Path: csiph.com!news.mixmin.net!weretis.net!feeder1.news.weretis.net!news.solani.org!.POSTED!not-for-mail From: "Christoph M. Becker" Newsgroups: comp.lang.javascript Subject: Re: Recursive function to find a node in the DOM Date: Thu, 20 Aug 2015 02:11:24 +0200 Organization: solani.org Lines: 40 Message-ID: References: <5530725.v0RXNFEj4j@PointedEars.de> <1885256.KGaLaWtVka@PointedEars.de> <4738754.gQ6MLv009L@PointedEars.de> <2800685.3l0yYTo2pD@PointedEars.de> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit X-Trace: solani.org 1440029477 1647 eJwFwYEBwCAMArCXrALtO2zD/09YwqPS2xAFXl5l+jOMHGa0VbsfLBXSpFVe8pS4w0D+AQtFEEA= (20 Aug 2015 00:11:17 GMT) X-Complaints-To: abuse@news.solani.org NNTP-Posting-Date: Thu, 20 Aug 2015 00:11:17 +0000 (UTC) User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.2.0 X-User-ID: eJwNysEBwCAIA8CVxIRQxqEi+4/Q3vscMp2gXPTxwbXoxczYaiyVHFls4hHOnPkruLvm+mupDwRTEIE= In-Reply-To: <2800685.3l0yYTo2pD@PointedEars.de> Cancel-Lock: sha1:LljheBlv8nBwgIqwUzw1n9Kqxu4= X-NNTP-Posting-Host: eJwFwYkRwDAIA7CVQnhcxiE+vP8IldLLiojKilTqwrtZ7VyTlq19D7GwM7x8MUB+Yk8eqvYHLU4SBg== Xref: csiph.com comp.lang.javascript:28548 On 16.08.2015 at 08:48, Thomas 'PointedEars' Lahn wrote: > I thought my illustration above in combination with what I said about the > property values under certaining conditions was, well, illustrative. > Perhaps you want to use a fixed-width font. Simply handing out the > algorithm would defeat the purpose of the exercise. > > […] Try again. Thanks for insisting. :) Albeit this exercise still seems rather somewhat academic to me, I found it interesting that it is indeed possible to walk the DOM *tree* iteratively. Apparently, I had overlooked the Node::parentNode property which makes that possible. A *simple* implementation of the iterative algorithm might be: function eachChildOf(baseNode, func) { var node = baseNode.firstChild; while (node) { func(node); if (node.firstChild) { node = node.firstChild; } else if (node.nextSibling) { node = node.nextSibling; } else { while (node.parentNode != baseNode && !node.parentNode.nextSibling) { node = node.parentNode; } if (node.parentNode != baseNode) { node = node.parentNode.nextSibling; } else { break; } } } } -- Christoph M. Becker