473,473 Members | 2,169 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Recursive function : driving me crazy...

Hello
I'm trying to display all DIV tags of a document :
Example :

+ <DIV id="1">
- <DIV id="1-1"></DIV>
</DIV>

+ <DIV id="2">
- <DIV id="2-1"></DIV>
+ <DIV id="2-2"></DIV>
- <DIV id="2-2-1"></DIV>
- <DIV id="2-2-2"></DIV>

etc...

I can retrieve all DIV using getElementsByTagName, but I don't know how
deep they can be nested.
I have no idea how to store informations such as : does a div has children
? if yes, how many ? in turn do the children have children ? At what level
is each DIV ? etc
Only a recursive function could do that, I think

Any help appreciated
Thanks.

Jul 20 '05 #1
6 1649
"Phil" <pa*******@pasdemail.com> wrote in message
news:Lo********************@giganews.com...
Hello
I'm trying to display all DIV tags of a document :
Example :

+ <DIV id="1">
- <DIV id="1-1"></DIV>
</DIV>

+ <DIV id="2">
- <DIV id="2-1"></DIV>
+ <DIV id="2-2"></DIV>
- <DIV id="2-2-1"></DIV>
- <DIV id="2-2-2"></DIV>

etc...

I can retrieve all DIV using getElementsByTagName, but I don't know how
deep they can be nested.
I have no idea how to store informations such as : does a div has children ? if yes, how many ? in turn do the children have children ? At what level
is each DIV ? etc
Only a recursive function could do that, I think

Any help appreciated
Thanks.

Your example above was missing a </DIV> tag and had another misplaced.

I may not understand your problem.

You say that you are "trying to display all DIV tags of a document" and that
you "can retrieve all DIV using getElementsByTagName"; what does it matter
how deep they are nested?

Below is a page that displays the id's of all <DIV> tags. Watch for
word-wrap.

<html>
<head>
<title>getElems.htm</title>
</head>
<body>
<DIV id="1">
<DIV id="1-1"></DIV>
</DIV>
<DIV id="2">
<DIV id="2-1"></DIV>
<DIV id="2-2">
<DIV id="2-2-1"></DIV>
<DIV id="2-2-2"></DIV>
</DIV>
</DIV>
<script language="javascript" type="text/javascript">
<!--
var divs = document.getElementsByTagName("DIV");
var what = "DIV tags:\n";
for (var i=0; i<divs.length; i++) {
what += "\n" + divs[i].id;
}
alert(what);
// -->
</script>
</body>
</html>
Jul 20 '05 #2
I may not understand your problem.

You say that you are "trying to display all DIV tags of a document" and that you "can retrieve all DIV using getElementsByTagName"; what does it matter
how deep they are nested?

Below is a page that displays the id's of all <DIV> tags. Watch for
word-wrap.


Thanks for your example, but I can already made this. What I want is really
displaying (document.write) the tree, with nodes, children and so forth
(Missing closing tags is not the point, I write this on the fly and I know
they are missing)

So if a div has children, I need to write the + sign, then the nested
children (if any) indented, etc
+ <DIV id="2">
- <DIV id="2-1"></DIV>
+ <DIV id="2-2"></DIV>
- <DIV id="2-2-1"></DIV>
- <DIV id="2-2-2"></DIV>
</DIV>


Jul 20 '05 #3
"Phil" <pa*******@pasdemail.com> writes:
Thanks for your example, but I can already made this. What I want is really
displaying (document.write) the tree, with nodes, children and so forth
(Missing closing tags is not the point, I write this on the fly and I know
they are missing)


I'll just write it as a string here, I'm sure you can convert the output
to your needs.

I can see two methods. One uses the document.getElementsByTagName("div")
collection and finds the structure by checking which elements are inside
each other. The other uses recursive descent on the tree. In both cases,
I build a datastructure of nodes on the form
node ::= {elem: DivNode, children: [array of divs nested inside DivNode]}

Using div collection, assuming that the divs are in the order the
start tags occour in the document (as I believe they should be):
---
// function that checks whether node2 is a predecessor of node1
function parentOf(node1,node2) {
while(node1!=null) {
if (node1 == node2) {return true;}
node1 = node1.parentNode;
}
return false;
}

function findDivsNest(elem) {
var divs = elem.getElementsByTagName("div");
var stack = [];
var topNode = {elem:elem,children:[]};
var currentNode = topNode;
for (var i = 0; i<divs.length;i++) {
var div = divs[i];
while (!parentOf(div,currentNode.elem)) {
currentNode = stack.pop();
}
var thisNode = {elem:div,children:[]};
currentNode.children.push(thisNode);
stack.push(currentNode);
currentNode = thisNode;
}
return topNode.children;
}
---

Recursive descent version:
---
function findDivsRec(node) {
if (node.nodeType != 1 && node.nodeType != 9) {
return []; // non-element, non-document node
}
var divs = [];
for (var chld = node.firstChild; chld != null; chld=chld.nextSibling) {
divs = divs.concat(findDivsRec(chld));
}
if (/^div$/i.test(node.tagName)) {
return [{elem:node,children:divs}];
} else {
return divs;
}
}
---

An example of how to output the data as text:
---
function divsToLines(divs,indent) {
indent = indent || "";
var nextIndent;
var result = [];
for (var i=0;i<divs.length;i++) {
var div=divs[i];
if (div.children.length > 0) {
nextIndent = nextIndent || indent + " "; // calc once
result.push(indent+" + <div id=\""+div.elem.id+"\">");
result = result.concat(divsToLines(div.children,nextIndent) );
result.push(indent+" <\/div>");
} else {
result.push(indent+" - <div id=\""+div.elem.id+"\"><\/div>");
}
}
return result;
}

function divsToString(divs) {
return divsToLines(divs).join("\n");
}
---

You can then test it with

alert(divsToString(findDivsRec(document)));
or
alert(divsToString(findDivsNest(document)));

If you want the output to be HTML, it's easy to fix.
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #4
Thank you. Have to study your code...it's a hard one for me :-)
"Lasse Reichstein Nielsen" <lr*@hotpop.com> a écrit dans le message de news:
hd**********@hotpop.com...
"Phil" <pa*******@pasdemail.com> writes:
Thanks for your example, but I can already made this. What I want is really displaying (document.write) the tree, with nodes, children and so forth
(Missing closing tags is not the point, I write this on the fly and I know they are missing)


I'll just write it as a string here, I'm sure you can convert the output
to your needs.

Jul 20 '05 #5
"Phil" <pa*******@pasdemail.com> wrote in message
news:_9********************@giganews.com...
I may not understand your problem.

You say that you are "trying to display all DIV tags of a document" and that
you "can retrieve all DIV using getElementsByTagName"; what does it matter how deep they are nested?

Below is a page that displays the id's of all <DIV> tags. Watch for
word-wrap.


Thanks for your example, but I can already made this. What I want is

really displaying (document.write) the tree, with nodes, children and so forth
(Missing closing tags is not the point, I write this on the fly and I know
they are missing)

So if a div has children, I need to write the + sign, then the nested
children (if any) indented, etc
+ <DIV id="2">
- <DIV id="2-1"></DIV>
+ <DIV id="2-2"></DIV>
- <DIV id="2-2-1"></DIV>
- <DIV id="2-2-2"></DIV>
</DIV>

Try this as-is; watch for word-wrap.
It may not be that elegant but it works.
<html>
<head>
<title>getElems.htm</title>
</head>
<body>

<DIV id="1">
<DIV id="1-1"></DIV>
</DIV>
<DIV id="2">
<DIV id="2-1"></DIV>
<DIV id="2-2">
<DIV id="2-2-1"></DIV>
<DIV id="2-2-2"></DIV>
</DIV>
</DIV>
<DIV id="3"></DIV>

<script language="javascript" type="text/javascript">
<!--
var diva = new Array();
var divi = 0;
var divs = document.getElementsByTagName("DIV");
var save = "|";
for (var i=0; i<divs.length; i++) {
if (save.indexOf("|"+divs[i].id+"|") < 0) {
getElement(divs[i],0);
}
}
function getElement(tag) {
var tags = tag.getElementsByTagName("DIV");
if (tag.childNodes[0] != null) {
save += tag.id + "|";
divi++;
diva[divi] = "+ " + tag.id;
for (var j=0; j<tag.childNodes.length; j++) {
getElement(tag.childNodes[j]);
save += tag.childNodes[j].id + "|";
}
} else {
divi++;
diva[divi] = "- " + tag.id;
}
}
var divx = "DIV tags:<br>";
for (var x=1; x<diva.length; x++) {
divx += "<br>" + diva[x];
}
document.write("<pre>" + divx + "</pre>");
// -->
</script>
</body>
</html>
Jul 20 '05 #6
Thanks a lot. I let you know how things go

"McKirahan" <Ne**@McKirahan.com> a écrit dans le message de news:
ODZGb.656303$HS4.4674451@attbi_s01...
"Phil" <pa*******@pasdemail.com> wrote in message
news:_9********************@giganews.com...

Jul 20 '05 #7

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

Similar topics

11
by: Shelly | last post by:
I set a session variable on error in the login page and then call the login page again. I test on that session variable but it shows as not set. I checked with an echo immediately after setting the...
4
by: dont bother | last post by:
This is really driving me crazy. I have a dictionary feature_vectors{}. I try to sort its keys using #apply sorting on feature_vectors sorted_feature_vector=feature_vectors.keys()...
4
by: Ryan Ternier | last post by:
I have a section of my project that is Driving me nuts. No one has been able to help that much on it, so i thought of posting it here in hopes someone could help. I need to print out an...
0
by: Shapper | last post by:
Hello, I have this code in Global.asax: Sub Session_Start(Sender As Object, E As EventArgs) Dim cookie As HttpCookie = Request.Cookies("MyCookie") If Not cookie Is Nothing Then...
5
by: Pupeno | last post by:
Hello, I am experiencing a weird behavior that is driving me crazy. I have module called Sensors containing, among other things: class Manager: def getStatus(self): print "getStatus(self=%s)"...
3
by: rashpal.sidhu | last post by:
Please help, this problem is driving me crazy !! I am using metaphone to create phonetic keys. When i run the module stand-a-lone it works fine. I'm trying to create a runner for informix...
5
by: mark4asp | last post by:
Every time the function below is called I get the alert. So I put a deliberate error in there and I check the value of (reportType=='MANDATE') in Firebug, which is found to be true. But still the...
6
by: RandomElle | last post by:
Hi there I'm hoping someone can help me out with the use of the Eval function. I am using Access2003 under WinXP Pro. I can successfully use the Eval function and get it to call any function with...
2
by: kheitmann | last post by:
OK, so I have a blog. I downloaded the "theme" from somewhere and have edited a few areas to suit my needs. There are different font themes within the page theme. Long story short, my "Text Posts"...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.