473,761 Members | 8,372 Online
Bytes | Software Development & Data Engineering Community
+ 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 getElementsByTa gName, 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 1668
"Phil" <pa*******@pasd email.com> wrote in message
news:Lo******** ************@gi ganews.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 getElementsByTa gName, 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 getElementsByTa gName"; 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="javas cript" type="text/javascript">
<!--
var divs = document.getEle mentsByTagName( "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 getElementsByTa gName"; 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*******@pasd email.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.getEle mentsByTagName( "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!=nu ll) {
if (node1 == node2) {return true;}
node1 = node1.parentNod e;
}
return false;
}

function findDivsNest(el em) {
var divs = elem.getElement sByTagName("div ");
var stack = [];
var topNode = {elem:elem,chil dren:[]};
var currentNode = topNode;
for (var i = 0; i<divs.length;i ++) {
var div = divs[i];
while (!parentOf(div, currentNode.ele m)) {
currentNode = stack.pop();
}
var thisNode = {elem:div,child ren:[]};
currentNode.chi ldren.push(this Node);
stack.push(curr entNode);
currentNode = thisNode;
}
return topNode.childre n;
}
---

Recursive descent version:
---
function findDivsRec(nod e) {
if (node.nodeType != 1 && node.nodeType != 9) {
return []; // non-element, non-document node
}
var divs = [];
for (var chld = node.firstChild ; chld != null; chld=chld.nextS ibling) {
divs = divs.concat(fin dDivsRec(chld)) ;
}
if (/^div$/i.test(node.tag Name)) {
return [{elem:node,chil dren:divs}];
} else {
return divs;
}
}
---

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

function divsToString(di vs) {
return divsToLines(div s).join("\n");
}
---

You can then test it with

alert(divsToStr ing(findDivsRec (document)));
or
alert(divsToStr ing(findDivsNes t(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/rasterTriangleD OM.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**********@ho tpop.com...
"Phil" <pa*******@pasd email.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*******@pasd email.com> wrote in message
news:_9******** ************@gi ganews.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 getElementsByTa gName"; 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="javas cript" type="text/javascript">
<!--
var diva = new Array();
var divi = 0;
var divs = document.getEle mentsByTagName( "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.getElements ByTagName("DIV" );
if (tag.childNodes[0] != null) {
save += tag.id + "|";
divi++;
diva[divi] = "+ " + tag.id;
for (var j=0; j<tag.childNode s.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$HS 4.4674451@attbi _s01...
"Phil" <pa*******@pasd email.com> wrote in message
news:_9******** ************@gi ganews.com...

Jul 20 '05 #7

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

Similar topics

11
1820
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 error session variable so I am 100% positive that it is set. The recursive entry to the login page echos a message that the error session variable is unset. Any clues? Here is the setting code and the testing code (commented out)"...
4
2533
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() sorted_feature_vector.sort() #feature_vector.keys()=sorted_feature_vector
4
6485
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 Ordered list. Ex. 1. Something
0
1310
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 Response.Write(" * Cookie Exists * ") If Not cookie.Values("culture") Is Nothing
5
1715
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)" % self return {"a": "b", "c": "d"} and then I have another module called SensorSingleton that emulates the
3
2282
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 which includes the function in order to allow me to call it from within a 4gl program. When i do this i get differences in the key that is produced????? This only happens when metahpone translates an x in a name. The stand
5
1770
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 alert comes up. Why? I checked the following watch expressions at the blah blah point. id = 5843 reportType = "MANDATE"
6
5931
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 or without parms. I know that any function that is passed to Eval() must be declared Public. It can be a Sub or Function, as long as it's Public. I even have it where the "function" evaluated by Eval can be in a form (class) module or in a standard...
2
3629
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" are supposed to be in the font: Georgia, but they are showing up in "Times New Roman"...blah! I can't find anything wrong in the code, but who am I trying to fool? I know nothing about this stuff. The code is below. The parts that I *think*...
0
9531
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9345
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10115
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9957
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9905
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9775
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8780
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6609
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5229
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

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.