473,320 Members | 1,987 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

can't do recursive function

Hi,
I'm trying to write a recursive fucntion that takes as parameters a
html div and an id. I have to recurse through all the children and
sub-children of the div and find the one that matches the id.
I have the following but it doesn't work well (algorighm issue) :

var cn = null;
function getChildElement(parent, childID){
for (var i=0; i<parent.childNodes.length; i++){
cn = parent.childNodes[i];
if(cn.getAttribute){

if(cn.getAttribute("id").toLowerCase().indexOf(chi ldID.toLowerCase()) >
-1 ){
return cn;
}else{
return getChildElement(parent.childNodes[i], childID);
}
}
}
return cn;
}
Can you help please ?

Jul 11 '06 #1
3 2924
What goes wrong? Why are you doing this anyway, ID's in a page should be
unique, so document.getElementById() should always work. You can check
with element.parentNode whether its in the correct location:

function checkParent(elem, requiredParent) {
while (elem.parentNode != null) {
if (elem.parentNode == requiredParent) {
return true;
}
elem = elem.parentNode;
}
return false;
}

Anyway, just a thought. The alogirth, looks good to me. You can invoke
getChildElement(cn, childID) instead of parent.childNodes[i]. Do you
know what goes wrong? does it give an error?

Vincent
Jul 11 '06 #2
sa*************@googlemail.com wrote:
Hi,
I'm trying to write a recursive fucntion that takes as parameters a
html div and an id. I have to recurse through all the children and
sub-children of the div and find the one that matches the id.
I have the following but it doesn't work well (algorighm issue) :

var cn = null;
You don't need cn as a global, you can keep it local.

function getChildElement(parent, childID){
var cn;
for (var i=0; i<parent.childNodes.length; i++){
It is more efficient to get the length of childNodes once and use that,
there might be lots of them!

for (var i=0; len<parent.childNodes.length; i<len; i++){

You could also use a while loop, the following goes backwards through
the nodes (which shouldn't be an issue here):

var i = parent.childNodes.length
while (i--) {

cn = parent.childNodes[i];
if(cn.getAttribute){

if(cn.getAttribute("id").toLowerCase().indexOf(chi ldID.toLowerCase()) >
-1 ){
A slightly simpler test (to me at least) is:

if (cn.id && cn.id.toLowerCase() == childID.toLowerCase()){

return cn;
So far so good, this will traverse all the child nodes and return a
match if one is found.
}else{
The above if will return if true and the function ends, so there is no
need for 'else'.

return getChildElement(parent.childNodes[i], childID);
But here you get into trouble. Firstly, 'cn' already refers to
parent.childNodes[i] so use it.

Next, as a speed optimisation, only call getChildElement if cn has
children:

if (cn.childNodes){
It should be quicker to test here than create a new recursive function
object and test it there.

Next, when you recursively call getChildElement, the result will be
returned to the spot it was called from. Your code returns whatever
the call returns immediately, without testing. Have getChildElement
return either an element, or something that evaluates to false. If you
get an element, it must be a match, so return it (and so on back up the
recursion chain...).

If you don't get an element, don't return, let the loop continue.
Something like:

var x = getChildElement(cn, childID);
if (x) return x;
}

}
}
}
return cn;
At this point you should return something that will evaluate to false
in an if test. You can explicitly return false if you like, but you
could do it by inference by returning nothing. That will result in the
function returning 'undefined' if no element is returned, and hence x
will be false in the test above - it depends on your coding standards
and preferences.
}
I get the feeling I'm doing your homework, so I'll leave pasting the
bits together to you. :-)

--
Rob

Jul 12 '06 #3

RobG wrote:
[...]
It is more efficient to get the length of childNodes once and use that,
there might be lots of them!

for (var i=0; len<parent.childNodes.length; i<len; i++){
Gosh, that's ugly...

for (var i=0, len=parent.childNodes.length; i<len; i++){

[...]

--
Rob

Jul 12 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: replace-this-with-my-name | last post by:
Hi. How do I return a string containing an entire menu-tree from a recursive function? Here is my current recursive function: function page_tree( $_i ){ //Call global mysql connection...
4
by: Derek Rhodes | last post by:
using Python 2.3.4 (#53, May 25 2004, 21:17:02) on win32 OK, I have a recursive function that should return a list, but doesn't <start session> def test(word): if type(word) == str:
4
by: Rodusa | last post by:
I am having problem to apply updates into this function below. I tried using cursor for updates, etc. but no success. Sql server keeps telling me that I cannot execute insert or update from inside...
7
by: mattrapoport | last post by:
Hello - I am kinda new to the HTML DOM so I apologize in advance for my ignorance. I have a table made from divs. I am trying to write a script that appends a new row to the table (by cloning...
41
by: Harry | last post by:
Hi all, 1)I need your help to solve a problem. I have a function whose prototype is int reclen(char *) This function has to find the length of the string passed to it.But the conditions...
5
by: Digital Puer | last post by:
I got this on an interview: Is it possible to write inline recursive functions? I said yes, but there is no guarantee that the compiler will definitely inline your code even if you write...
10
by: pereges | last post by:
How to to go about this ? Suppose a malloc inside a recursive function has failed and you want to set the error flag and return it to the calling function(the one which called the recursive...
3
dlite922
by: dlite922 | last post by:
I need to get a list of employees out of a database table. I need to end up with an array of ids (primary keys) such as Array(03,9,2,5,1) The employee table has a self reference so that...
4
by: ThEoNeAnDOnLy | last post by:
I recently had an issue with my recursive project in class. Here is the code. // Recursion.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include...
3
by: Davy | last post by:
Hi all, Sometimes I need to pass same parameter in recursive function. From my point of view, the style is redundant, and I don't what to use some global style like self.A, self.B, Is there any...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.