473,385 Members | 1,927 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,385 software developers and data experts.

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) {
commonplaceLogMain.cplNodes += '<' + node.nodeName + '>' + str + '</'
+ node.nodeName + '>' ;
};

this.iterate = function (r) {
var me = this, node = r.startContainer, 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(offset);
}
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.nextSibling) {
node = node.parentNode;
offset = node.childNodes.length;
} else {
node = node.nextSibling;
offset = 0;
}
}
return true;
};
}
Feb 4 '08 #1
4 2337
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...@gmail.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(allowed_html, parentNode)) {
if (in_array(open_tags, parentNode) == false)
{
//close old tag
commonplaceLogMain.cplNodes += '</' +
parentNode.nodeName.toLowerCase() + '';
break;
}
if (in_array(open_tags, parentNode)) {
//open new tag
commonplaceLogMain.cplNodes += '<' +
parentNode.nodeName.toLowerCase() + '';
break;
}
}
parentNode = parentNode.parentNode;
}
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(allowed_html, parentNode)) {
if (in_array(open_tags, parentNode) == false)
{
//close old tag
commonplaceLogMain.cplNodes += '</' +
parentNode.nodeName.toLowerCase() + '';
break;
}
if (in_array(open_tags, parentNode)) {
//open new tag
commonplaceLogMain.cplNodes += '<' +
parentNode.nodeName.toLowerCase() + '';
break;
}
}
parentNode = parentNode.parentNode;
}
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.nextSibling 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.nextSibling 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
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" ...
1
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,...
1
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...
2
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...
4
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...
4
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...
10
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...
1
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...
0
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...
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,...

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.