473,657 Members | 2,652 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Traversing the DOM & maintaining node hierarchy

I've been working on something that deals with handling a user's
selection within the DOM and I'm tripping up on one last, but crucial,
detail.
Forgive me for the length of the code, but my question is pretty
straightforward and my brain hasn't been working.

Problem: The way I'm iterating through the nodes doesn't allow me to
preserve the node hierarchy.

Instead of:
<div></div><b></b>text

I want:
<div><b>text</b></div>

function RangeIterator() {
this.onNode = function (str, node) {
commonplaceLogM ain.cplNodes += '<' + node.nodeName + '>' + str + '</'
+ node.nodeName + '>' ;
};

this.iterate = function (r) {
var me = this, node = r.startContaine r, offset = r.startOffset,
finalNode = r.endContainer, finalOffset = r.endOffset;

function visitNode(node, offset) {
var isFinal = (node == finalNode), lastChildIndex, i, c, str = '';

switch (node.nodeType) {
case 3:
case 4:
case 7:
case 8:
str = node.nodeValue;
if (isFinal) {
str = str.substring(0 , finalOffset);
}
if (offset) {
str = str.substring(o ffset);
}
me.onNode(str, node);
break;
default:
me.onNode(str, node);
lastChildIndex = isFinal ? finalOffset : node.childNodes .length;
for (i = offset, c = node.childNodes .item(i); i < lastChildIndex; c =
c.nextSibling, i++) {
if (!visitNode(c, 0)) {
return false;
}
}
}
return !isFinal;
}

while (visitNode(node , offset)) {
if (!node.nextSibl ing) {
node = node.parentNode ;
offset = node.childNodes .length;
} else {
node = node.nextSiblin g;
offset = 0;
}
}
return true;
};
}
Feb 4 '08 #1
4 2356
On Feb 4, 8:04*am, matth <matt...@gmail. comwrote:
Bummer, the closing tag is the important part! But thanks though, I'll
take a look, it'll be cool to see how you traverse the DOM anyway. I
might learn a thing or two.- Hide quoted text -
Let's say you keep up with your 'opening tags' in a string called
startTags

You could also create a string to keep up with the closing tags called
endTags

endTags = '';

You could have a little function like:

function makeEndTags(tag ){
endTags = tag + endTags;
}

Then when you come to a tag, like "<body>", you could do

makeEndTags('</body>')

Then say the next 'tag' is '<div>' do makeEndTags('</div>')

then if the next is '<p>' do makeEndTags('</p>')

so that you construct a string in endTags that looks like this

</p></div></body>

So at the end you print

startTags + endTags and you get

<body><div><p ></p></div></body>

And just insert whatever formatting you like in the two strings as you
go.


Feb 4 '08 #2
On Feb 4, 10:42 am, Doug Gunnoe <douggun...@gma il.comwrote:
On Feb 4, 8:04 am, matth <matt...@gmail. comwrote:
Bummer, the closing tag is the important part! But thanks though, I'll
take a look, it'll be cool to see how you traverse the DOM anyway. I
might learn a thing or two.- Hide quoted text -

Let's say you keep up with your 'opening tags' in a string called
startTags

You could also create a string to keep up with the closing tags called
endTags

endTags = '';

You could have a little function like:

function makeEndTags(tag ){
endTags = tag + endTags;

}

Then when you come to a tag, like "<body>", you could do

makeEndTags('</body>')

Then say the next 'tag' is '<div>' do makeEndTags('</div>')

then if the next is '<p>' do makeEndTags('</p>')

so that you construct a string in endTags that looks like this

</p></div></body>

So at the end you print

startTags + endTags and you get

<body><div><p ></p></div></body>

And just insert whatever formatting you like in the two strings as you
go.
I started out with something very similiar to what you pointed out,
but that solution breaks down once you get to something like this:
<div><b></b></div><div><b></b></div>

When is it the right time to add those end tags? Here's a copy of an
approach that I tried but never finished up:
// TESTING

var allowed_html = new Array('b', 'u', 'i', 'h1', 'h2',
'h3', 'h4', 'code', 'pre', 'a', 'li', 'p', 'br');
var parentNode = node.parentNode ;
var open_tags = new Array();
while (parentNode) {
if (in_array(allow ed_html, parentNode)) {
if (in_array(open_ tags, parentNode) == false)
{
//close old tag
commonplaceLogM ain.cplNodes += '</' +
parentNode.node Name.toLowerCas e() + '';
break;
}
if (in_array(open_ tags, parentNode)) {
//open new tag
commonplaceLogM ain.cplNodes += '<' +
parentNode.node Name.toLowerCas e() + '';
break;
}
}
parentNode = parentNode.pare ntNode;
}
function in_array (array, value) {
var i;
for (i = 0; i < this.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
Feb 4 '08 #3
On Feb 4, 11:24 am, matth <matt...@gmail. comwrote:
>
I started out with something very similiar to what you pointed out,
but that solution breaks down once you get to something like this:
<div><b></b></div><div><b></b></div>
You're right.
When is it the right time to add those end tags? Here's a copy of an
approach that I tried but never finished up:
// TESTING

var allowed_html = new Array('b', 'u', 'i', 'h1', 'h2',
'h3', 'h4', 'code', 'pre', 'a', 'li', 'p', 'br');
var parentNode = node.parentNode ;
var open_tags = new Array();
while (parentNode) {
if (in_array(allow ed_html, parentNode)) {
if (in_array(open_ tags, parentNode) == false)
{
//close old tag
commonplaceLogM ain.cplNodes += '</' +
parentNode.node Name.toLowerCas e() + '';
break;
}
if (in_array(open_ tags, parentNode)) {
//open new tag
commonplaceLogM ain.cplNodes += '<' +
parentNode.node Name.toLowerCas e() + '';
break;
}
}
parentNode = parentNode.pare ntNode;
}
function in_array (array, value) {
var i;
for (i = 0; i < this.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
When looking at my example I found a logic error. It does not traverse
back up the tree like it should. Anyway, I thought of the solution but
have not had time try it.

Create an array for the end tags 'stack = []'. When going down the
tree, push the end tags onto the array.

stack.push('</' + node.nodeName + '>');

anytime you move to node.nextSiblin g or node.parentNode do stack.pop()
and add that to the string.

This way it should only add the end tags at the right time.


Feb 5 '08 #4
When looking at my example I found a logic error. It does not traverse
back up the tree like it should. Anyway, I thought of the solution but
have not had time try it.

Create an array for the end tags 'stack = []'. When going down the
tree, push the end tags onto the array.

stack.push('</' + node.nodeName + '>');

anytime you move to node.nextSiblin g or node.parentNode do stack.pop()
and add that to the string.

This way it should only add the end tags at the right time.
matth,

I don't know if you ever found a solution to this, but it was a pretty
good problem.

No doubt one that was already solved a thousand times, but hey, what
is time for anyway, right? :)

So I finally got a chance to try my use of a stack to track the end
tags and insert them at the right time and I think it works.

http://polisick.com/domTraverseExample.html

Doug
Feb 12 '08 #5

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

Similar topics

3
4275
by: gsb | last post by:
I'd like to get the offset coordinates, top & left, of an embedded Flash movie. <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.ca b#version=7,0,14,0" id="tabMenu" width="720" height="420"> <param name="movie" value="tabMenu.swf"> <param name="menu" value="false">
1
1436
by: alfred | last post by:
Hi my question is on traversing a tree with DOM. how would I be able to traverse 2 trees at the same time. I have 2 XML documents, with similar nodes. I would like to traverse 1 xml document, if I found a node that matches another node in the other document, I would like to update attributes in the other document. I know you can recursive traverse a document, my problem is to traverse 2 document at the same time, thanks
1
1908
by: Abdul H S via DotNetMonster.com | last post by:
I am facing difficulty to make sql on the basis of user selected node in treeview.After selection of the particulare treenode I want to traverse the hierarchy up to rootnode.plz help me regarding this. Thanks
2
2672
by: kevin | last post by:
I would like to remember the state of the nodes after the treeview gets disposed, but not necessarily after the app terminates so I don't need a disk file. I was thinking about using the tag property, but I am already using it, so then I though about making a custom treeiew using inheritance and adding another tag type property? Any clues? kevin
4
4868
by: plmanikandan | last post by:
Hi, I am new to link list programming.I need to traverse from the end of link list.Is there any way to find the end of link list without traversing from start(i.e traversing from first to find the next for null).Is there any way to find the length of linked list in c.My need is to traverse from the end to 5th node Regards, Mani
4
5531
by: Christian Rühl | last post by:
Good Day, folks! I'm having a problem traversing an XmlDocument tree in C#. I only want to access the InnerText of the leafs and the names of their ancestors and show them in a richTextBox. But if I go like this I get the InnerText of all the nodes and the outcome in my richTextBox is just a mess. The XML files i want to handle here have about 2300 nodes, so that accessing some nodes directly is just impossible.
10
4279
by: Rik | last post by:
Hi all, I usually don't really use javascript, but for a pretty big form, I'm trying the following: I've got arbitrarily deep nested unorderd list, with in every <li3 checkboxes. It's for granting users certain rights, and rights are inherited (or unset) downwards. To directly illustrate what certain changes will do for the user, I want to
1
2215
by: flavourofbru | last post by:
Hello, I am trying to traverse and tree and want to assign the node id for each node in the tree. It would be great if someone helps me with it. Here is the code which i am using and the problem is the nodes in the tree are repeating everytime and i want to visit each node only once and assign the node id to it. protected void walk(TreeModel model, Object o){ int cc;
0
8392
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
8305
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
8825
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
8605
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
7324
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
4151
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...
0
4302
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
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 we have to send another system
2
1611
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.