Forum How do I...?

Javascript and sourceIndex or compareDocumentPosition

ksaylor
I have found some goods tutorials on creating a TOC using javascript. I have a document that ends up being about 450 pages, and each chapter has multiple sub heading, so I create a TOC for h1,h2,h3,h4, and h5. The thing is that the TOC get created just fine in Chrome, but it seems that the Prince javascript engine does not like my javascript code. Keep in mind, that I have to find all the elements for the headers and keep them in order so that my TOC looks something like this:

1. Something
-1.1
--1.1.2
2. Something else
-2.1
-2.2


Instead of:

1. Something
2. Something else
-1.1
-2.1
-2.2
--1.1.2


Here's the code that returns the array of elements in order code (kind of ugly, but gets the job done):

function getElementsByTagNames(list,obj) {
    if (!obj) var obj = document;
    var tagNames = list.split(',');
    var resultArray = new Array();
    for (var i=0;i<tagNames.length;i++) {
        var tags = obj.getElementsByTagName(tagNames[i]);
        for (var j=0;j<tags.length;j++) {
            resultArray.push(tags[j]);
        }
    }
    var testNode = resultArray[0];
    if (!testNode) return [];
    if (testNode.sourceIndex) {
        resultArray.sort(function (a,b) {
                return a.sourceIndex - b.sourceIndex;
        });
    }
    else if (testNode.compareDocumentPosition) {
        resultArray.sort(function (a,b) {
                return 3 - (a.compareDocumentPosition(b) & 6);
        });
    }
    return resultArray;
}


It seems that Prince either doesn't like sourceIndex or compareDocumentPosition. The output from Prince gives me the non-sorted version of the TOC. I have a workaround right now where I copy the html using Chrome's Javascript console and then I paste that resulting html into the file before running prince. Though this method works, I'd like to just use the javascript option.

I am using Mac OS X (Mountain Lion) if that makes any difference.
mikeday
We plan to support compareDocumentPosition in the next release of Prince. In the meantime, it may be possible to write a JavaScript stub for this DOM method that performs the necessary comparison.
mikeday
Prince 10 now supports compareDocumentPosition. :)