473,729 Members | 2,344 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Determining document structure

Does anyone have a clever algorithm for generating an outline of the
current document from (client-side) javascript using DOM methods?

For example, let's say I predictably have a document structured
hierarchically with <h1>...<h6tag s. I want to generate an outline of
the document wherein I have nested lists of the contents of the headers.
Take for example the following snippet of a fictional legal document:

------------
<h1>Main Title</h1>
<h2>Section One</h2>
<h3>Paragraph A</h3>
<p>Congress shall make no law regarding the production of baggy clown
pants.</p>
<h3>Paragraph B</h3>
<p>Congress shall make now law restricting the use of said clown pants,
for any purpose otherwise legal.</p>

<h2>Section Two</h2>
<h3>Paragraph A</h3>
<p>Etc, etc.</p>
----------

From this I would want to generate
------
<ul>
<li>Main Title
<ul>
<li>Section One
<ul>
<li>Paragraph A</li>
<li>Paragraph B</li>
</ul>
</li>
<li>Section Two
<ul>
<li>Paragraph A</li>
</ul>
</li>
</ul>
------

using DOM methods. There are two ways I can think of to do this, being:
1) Scan through a flat list of all content nodes in succession
[document.getEle mentsByTagName( "*")] and keep a structure of any <hX>
tags that are encountered by attaching any <hNtag to the most recent
<hN-1tag.

or

2) Get a list of each header level [document.getEle mentsByTagName( "h1"),
document.getEle mentsByTagName( "h2"), etc...] and somehow merge them and
sort them by order of appearance in the document. Then use that list to
generate the structure.

Method (2) seems more efficient but also more complicated. Before I
start on this, I wanted to see if anyone has done this before or has a
clever algorithm that I haven't thought of.

Thanks,
Jeremy
Jan 29 '07 #1
5 1579
<script language="JavaS cript" type="text/javascript">
<!--

var _xmlStr = '';

function crawlXML(doc) { // Crawls an XML
document
if(doc.hasChild Nodes()) { // If present
element has children
_xmlStr+='<ul>< li>'+doc.tagNam e+''; // Display current
tag name
for(var i=0; i<doc.childNode s.length; i++) { // for each child
node on current level
crawlXML(doc.ch ildNodes[i]); // Call this
function recursively
} // end for loop
_xmlStr+='<\/li><\/ul>'; // Close the
list item.
} else { // current element
has no children
_xmlStr+=doc.no deValue; // So display the
value of the data
} // End childNode check
} // End crawlXML

function startup() {
crawlXML(docume nt);
document.getEle mentById('outpu tdiv').innerHTM L=_xmlStr;
}

//-->
</script>
<body onload="startup ()">
<div id='outputdiv'> </div>
</body>

--
http://www.hunlock.com -- Musings in Javascript, CSS.
$FA
Jan 29 '07 #2
On Mon, 29 Jan 2007 11:55:14 -0800, in comp.lang.javas cript Jeremy
<je****@pinacol .com>
<si************ ****@newsfe06.p hxwrote:
>| Does anyone have a clever algorithm for generating an outline of the
| current document from (client-side) javascript using DOM methods?
|
| For example, let's say I predictably have a document structured
| hierarchically with <h1>...<h6tag s. I want to generate an outline of
| the document wherein I have nested lists of the contents of the headers.
| Take for example the following snippet of a fictional legal document:
|
| ------------
| <h1>Main Title</h1>
| <h2>Section One</h2>
| <h3>Paragraph A</h3>
| <p>Congress shall make no law regarding the production of baggy clown
| pants.</p>
| <h3>Paragraph B</h3>
| <p>Congress shall make now law restricting the use of said clown pants,
| for any purpose otherwise legal.</p>
|
| <h2>Section Two</h2>
| <h3>Paragraph A</h3>
| <p>Etc, etc.</p>
| ----------
|
| From this I would want to generate
| ------
| <ul>
| <li>Main Title
| <ul>
| <li>Section One
| <ul>
| <li>Paragraph A</li>
| <li>Paragraph B</li>
| </ul>
| </li>
| <li>Section Two
| <ul>
| <li>Paragraph A</li>
| </ul>
| </li>
| </ul>
| ------
|
| using DOM methods. There are two ways I can think of to do this, being:
| 1) Scan through a flat list of all content nodes in succession
| [document.getEle mentsByTagName( "*")] and keep a structure of any <hX>
| tags that are encountered by attaching any <hNtag to the most recent
| <hN-1tag.
|
| or
|
| 2) Get a list of each header level [document.getEle mentsByTagName( "h1"),
| document.getEle mentsByTagName( "h2"), etc...] and somehow merge them and
| sort them by order of appearance in the document. Then use that list to
| generate the structure.
|
| Method (2) seems more efficient but also more complicated. Before I
| start on this, I wanted to see if anyone has done this before or has a
| clever algorithm that I haven't thought of.
I found these couple of entries, using google

http://www.phpied.com/suddenly-structured-articles/
http://www.bazon.net/mishoo/toc.epl
---------------------------------------------------------------
jn******@yourpa ntsyahoo.com.au : Remove your pants to reply
---------------------------------------------------------------
Jan 29 '07 #3

On Jan 29, 9:55 pm, Jeremy <jer...@pinacol .comwrote:
Does anyone have a clever algorithm for generating an
outline of the current document from (client-side)
javascript using DOM methods?
Note that there's a DSL for that type of processing. The
following is probably of mostly theoretical interest at
the moment, since JavaScript XSLT API support across
browsers seems to be patchy AFAICT, and we are probably
not going to see any kind of XSLT2 support for a few years,
but still, the fact that you can use XSLT to juggle your
nodes instead of crawling through them using DOM API is
something to keep in mind.
For example, let's say I predictably have a document
structured hierarchically with <h1>...<h6tag s. I want
to generate an outline of the document wherein I have
nested lists of the contents of the headers. Take for
example the following snippet of a fictional legal
document:

<h1>Main Title</h1>
<h2>Section One</h2>
<h3>Paragraph A</h3>
<p>Congress shall make no law regarding the production of
baggy clown pants.</p>
<h3>Paragraph B</h3>
<p>Congress shall make now law restricting the use of
said clown pants, for any purpose otherwise legal.</p>
<h2>Section Two</h2>
<h3>Paragraph A</h3>
<p>Etc, etc.</p>
The following code might seem inefficient for a task this
simple, but if you have to do something more complicated
with your document, using the built-in XSLT processor
becomes much more appealing:

<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
function genToc ( )
{
var xformSrc =
' <xsl:styleshe et version="1.0" ' +
' xmlns:xsl="http ://www.w3.org/1999/XSL/Transform"' +
' <xsl:output method="html"/' +
' <xsl:template match="@*|node( )"' +
' <xsl:apply-templates ' +
' select="@*|node ()"/' +
' </' + 'xsl:template' +
' <xsl:template match="body"' +
' <ul' +
' <xsl:apply-templates ' +
' select=".//h1"/' +
' </' + 'ul' +
' </' + 'xsl:template' +
' <xsl:template match="h1|h2|h3 |h4|h5|h6"' +
' <xsl:variable name="curName" ' +
' select="local-name()"/' +
' <xsl:variable name="subName" ' +
' select= ' +
' "concat(\'H \',' +
' 1+number(substr ing-after(' +
' local-name(),\'H\'))) "/' +
' <li' +
' <xsl:apply-templates select="text()" ' +
' mode="yank-text"/' +
' <ul' +
' <xsl:apply-templates ' +
' select= ' +
' "following: :*[(preceding::*' +
' [local-name()=$curName][1])' +
' [generate-id(.)=generate-id(' +
' current())]][local-name()=' +
' $subName]"/' +
' </' + 'ul' +
' </' + 'li' +
' </' + 'xsl:template' +
' <xsl:template match="text()" ' +
' mode="yank-text"' +
' <xsl:value-of select="."/' +
' </' + 'xsl:template' +
' </' + 'xsl:stylesheet ' ;
var parser = new DOMParser ( ) ;
var xform =
parser . parseFromString
(
xformSrc , 'text/xml'
) ;
var proc = new XSLTProcessor ( ) ;
proc . importStyleshee t ( xform ) ;
var toc =
proc . transformToFrag ment
(
document , document
) ;
var tocDiv = document . getElementById ( 'toc' ) ;
tocDiv . appendChild ( toc ) ;
}
</script>
</head>
<body onload=" genToc ( ) ; ">
<div id="toc"></div>
<h1>Main Title</h1>
<h2>Section One</h2>
<h3>Paragraph A</h3>
<p>Congress shall make no law regarding the production of
baggy clown pants.</p>
<h3>Paragraph B</h3>
<p>Congress shall make now law restricting the use of said
clown pants, for any purpose otherwise legal.</p>
<h2>Section Two</h2>
<h3>Paragraph A</h3>
<p>Etc, etc.</p>
</body>
</html>

Only works in Gecko-based UA's (tested in Firefox 1.5.0.7).

--
Pavel Lepin

Jan 30 '07 #4
Jeremy wrote:
Does anyone have a clever algorithm for generating an outline of the
current document from (client-side) javascript using DOM methods?

For example, let's say I predictably have a document structured
hierarchically with <h1>...<h6tag s. I want to generate an outline of
the document wherein I have nested lists of the contents of the headers.
Take for example the following snippet of a fictional legal document:

------------
<h1>Main Title</h1>
<h2>Section One</h2>
<h3>Paragraph A</h3>
<p>Congress shall make no law regarding the production of baggy clown
pants.</p>
<h3>Paragraph B</h3>
<p>Congress shall make now law restricting the use of said clown pants,
for any purpose otherwise legal.</p>

<h2>Section Two</h2>
<h3>Paragraph A</h3>
<p>Etc, etc.</p>
----------

From this I would want to generate
------
<ul>
<li>Main Title
<ul>
<li>Section One
<ul>
<li>Paragraph A</li>
<li>Paragraph B</li>
</ul>
</li>
<li>Section Two
<ul>
<li>Paragraph A</li>
</ul>
</li>
</ul>
------

using DOM methods. There are two ways I can think of to do this
Just wander down the DOM and create a series of nested ULs with the
heading text in LIs. It's a tad easier using a bit of innerHTML, but not
much. Here's a pure DOM method:

<title>Outlin e</title>
<script type="text/javascript">

var genTOC = (function () {

var tocHTML = '';
var level = 1;
var tagRE = /^h\d+/;
var toc = genNode('ul');
var currentEl = toc;

function getText (el) {
if (el.textContent ) {return el.textContent; }
if (el.innerText) {return el.innerText;}
if (typeof el.innerHTML == 'string') {
return el.innerHTML.re place(/<[^<>]+>/g,'');
}
}
function genNode(t) { return document.create Element(t);}
function genText(s) { return document.create TextNode(s);}
function previous(el, t){
el = el.parentNode;
while(el.tagNam e.toLowerCase() != t) {
el = el.parentNode;
}
return el;
}

return {
start: function (tocEl, startEl) {
if (!document.getE lementById)
return;
if (typeof tocEl == 'string')
tocEl = document.getEle mentById(tocEl) ;
if (typeof startEl == 'string')
startEl = document.getEle mentById(startE l);

startEl = startEl || document.body;
this.run(startE l);
tocEl.appendChi ld(toc);
},

run: function(el){
var kid, kids = el.childNodes;
var t, thisLevel;

for (var i=0, len=kids.length ; i<len; i++) {
kid = kids[i];

if (kid.tagName && tagRE.test(kid. tagName.toLower Case())) {
thisLevel = kid.tagName.sub string(1);
if (thisLevel level) {
currentEl.appen dChild(genNode( 'ul'));
currentEl = currentEl.lastC hild;
level++;
} else {
while (thisLevel < level) {
currentEl = previous(curren tEl, 'ul');
level--;
}
}
t = genNode('li');
t.appendChild(g enText(getText( kid)))
currentEl.appen dChild(t);
}
if (kid.childNodes ) {this.run(kid); }
}
}
}
})();

window.onload = function(){genT OC.start('tocDi v');}
</script>

<body>
<div id="tocDiv"></div>
<div>
<h1>Heading 1</h1>
<p>Lorem Ipsum</p>
<h2>Heading 1.1</h2>
<p>Lorem Ipsum</p>
<h2>Heading 1.2</h2>
<p>Lorem Ipsum</p>
<h3>Heading 1.2.1</h3>
<p>Lorem Ipsum</p>
<h3>Heading 1.2.2</h3>
<p>Lorem Ipsum</p>
<h3>Heading 1.2.3</h3>
<p>Lorem Ipsum</p>
<h2>Heading 1.3</h2>
<div>
<p>Lorem Ipsum</p>
<h3>Heading 1.3.1</h3>
<p>Lorem Ipsum</p>
<h3>Heading 1.3.2</h3>
<p>Lorem Ipsum</p>
</div>
<div>
<h1>Heading 2</h1>
<p>Lorem Ipsum</p>
<h2>Heading 2.1</h2>
<p>Lorem Ipsum</p>
<h3>Heading 2.1.1</h3>
<p>Lorem Ipsum</p>
<h3>Heading 2.1.2</h3>
</div>
</div>
</body>
Lightly tested.

--
Rob
Jan 30 '07 #5
RobG wrote:
Jeremy wrote:

Just wander down the DOM and create a series of nested ULs with the
heading text in LIs. It's a tad easier using a bit of innerHTML, but not
much. Here's a pure DOM method:

<code snipped>
Thanks to all that replied to this question. I've looked at all the
links and ideas you came up with and wrote with an implementation I'm
pretty happy with.

Jeremy
Jan 31 '07 #6

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

Similar topics

2
5423
by: Luca | last post by:
I have the following problem: I'm developing a system where there are some processes that communicate each other via message queues; the message one process can send to another process is as follows: ****************************************** struct ST_MSG { int iType; char aData; }
1
26956
by: Simon Wigzell | last post by:
I am adapting a javascript pulldown menu system to my dynamic website generator - the arrays that hold the menu items information are read from a database and will be different for different users of my system. Unfortunately the javascript menu system requires that each menu cell's width be dimensioned. if I don't hard code a large enough value then long menu item names are trimmed, besides the fact that it then looks ugly for most menu...
5
11984
by: Audrius | last post by:
Hello, Firstly, I'm not good at JS, so please be patient :) I have a quite complicated page structure, where a lot of frames are created dynamically (same applies to their names). How can I make each of these frames print itself's name e.g. using alert? I know the name of the parent frame, and I can include any js in each dynamically created frame's header.
18
4928
by: Robert | last post by:
Hi! I was wondering if the was any way to determine the state of the caps lock key, on or off. Of course I can capture the key events and see whether the caps lock is pressed, but that does not help. I have seen some example that looks at the characters entered in an input field to determine if the caps lock is on, but I was wondering if something is possible that is a bit more immediate to report the caps
4
5016
by: Jim | last post by:
Hi I'm looking to take an existing XML document, query for certain nodes, and 'recreate' the document with just the relevant nodes. I'm currently using XPath - I have established the pattern that returns the required child nodes from the document, but am struggling to find a good statergy for recreating the file Here is an excert of my XML file <resource_data><planets><planet...
1
963
by: CES | last post by:
I'm looking for a JavaScript/.net replacement for Netscape's window.outerWidth that will work in IE and was wondering is their a way of determining if the search/history/favorites/etc. sidebar is open ??? Any other suggestion on how to find the total with of the IE window would be appreciated. Thanks CES
4
2160
by: petermichaux | last post by:
Hi, I'm hoping for a reason I'm wrong or an alternate solution... I'd like to be able to dynamically include some javascript files. This is like scriptaculous.js library but their solution is broken in Firefox 1.5.0.1 on OS X. What happens with the Scriptaculous library is this In the html document the author only has to include one line
3
4882
by: Steve Sobol | last post by:
I need to use JavaScript and the DOM to determine the available amount of browser space - the total size of the browser window minus whatever space is used by chrome. window.innerHeight and window.innerWidth seem to work fine in Opera 8 and Firefox 1.5. In IE, I've read that you need to use document.body.clientHeight and .clientWidth but that seems to only give you the dimensions of the box created by your <body> tag. Whatever...
53
4954
by: Aaron Gray | last post by:
Due to M$'s stupidity in not making DOMElements first class citizens the following will not work :- function isElement( o) { return o instanceof Element } It works for FF, Opera and Safari.
0
8917
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
8761
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
9426
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...
1
9200
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
9142
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
6022
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();...
1
3238
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
2680
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2163
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.