Forum How do I...?

JavaScript, Iterating Over And Changing Found Items

conner_bw
I'm trying to run a JavaScript that converts certain headers to roman numerals.

The following code works in my browsers, but not Prince XML. That is anything identified as <h3 class="part-number"> gets converted to a roman numeral in Chrome and Firefox:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
	<head>
		<title>Test</title>
		<style type="text/css">
		h3.part-number:before {
			content: "Part ";
			text-transform: uppercase;
		}
		</style>
		<script type="text/javascript">
		// <![CDATA[
		function rome(N,s,b,a,o,t){
		  t=N/1e3|0;N%=1e3;
		  for(s=b='',a=5;N;b++,a^=7)
			for(o=N%a,N=N/a^0;o--;)
			  s='IVXLCDM'.charAt(o>2?b+N-(N&=~1)+(o=1):b)+s;
		  return Array(t+1).join('M')+s;
		}

		function doSomething() {
			var list = document.querySelectorAll("h3.part-number");
			for(var i = 0; i < list.length; i++) {
				var item = list.item(i);
				item.innerHTML = rome(item.innerHTML);
			}
		}
		window.onload = doSomething;
		// ]]>
		</script>
	</head>
	<body>
		<div class="part" id="main-body">
			<h3 class="part-number">1</h3>
			<h1>General Styles and Layout Test</h1>
		</div>
		<div class="chapter" id="long-text">
			<h3 class="chapter-number">1</h3>
			<h2>A Chapter with Long Text</h2>
			<div class="ugc">
				<p>In a village of La Mancha, the name of which I have no desire to call to mind, there lived not long since one of those gentlemen that keep a lance in the lance-rack, an old buckler, a lean hack, and a greyhound for coursing. An olla of rather more beef than mutton, a salad on most nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra on Sundays, made away with three-quarters of his income. The rest of it went in a doublet of fine cloth and velvet breeches and shoes to match for holidays, while on week-days he made a brave figure in his best homespun. He had in his house a housekeeper past forty, a niece under twenty, and a lad for the field and market-place, who used to saddle the hack as well as handle the bill-hook. The age of this gentleman of ours was bordering on fifty; he was of a hardy habit, spare, gaunt-featured, a very early riser and a great sportsman. They will have it his surname was Quixada or Quesada (for here there is some difference of opinion among the authors who write on the subject), although from reasonable conjectures it seems plain that he was called Quexana. This, however, is of but little importance to our tale; it will be enough not to stray a hair&#8217;s breadth from the truth in the telling of it.</p>
			</div>
		</div>
		<div class="chapter" id="standard-layout-tests">
			<h3 class="chapter-number">2</h3>
			<h2>Standard Layout Tests</h2>
			<div class="ugc">
				<h2>Default Paragraph</h2>
				<p>Lorem Ipsum is <a href="http://wordpress.org">simply dummy</a> text of the printing and &#8220;typesetting industry&#8221;. Lorem Ipsum has been the industry&#8217;s standard dummy text ever since the 1500s, when an unknown &#8220;printer&#8221; took a galley of type and scrambled it to make a type speci<a href="http://wordpress.org">men book. It has survived not only fi</a>ve centuries, but also the leap into electronic typesetting, remaining essentially <span class="annotation">unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum</span>.</p>
				<h2>Left align</h2>
				<p style="text-align: left;">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed odio nibh, tincidunt adipiscing, pretium nec, tincidunt id, enim. Fusce scelerisque nunc vitae nisl. <span class="annotation">Quisque quis urna in velit dictum pellentesque. Vivamus a quam. Curabitur eu tortor</span> id turpis tristique adipiscing. Morbi blandit. Maecenas vel est. Nunc aliquam, orci at accumsan commodo, libero nibh euismod augue, a ullamcorper velit dui et <span class="annotation">purus</span>. Aenean volutpat, ipsum ac imperdiet fermentum, dui dui suscipit arcu, vitae dictum <span class="annotation">purus</span> diam ac ligula. Praesent enim nunc, pretium eget, tincidunt in, semper at, mauris. Etiam nec ligula. Aenean <span class="annotation">purus</span> pede, sagittis at, blandit a, dignissim nec, elit. <span class="annotation">Etiam nunc. Praesent molestie consectetuer leo. Etiam blandit leo mollis velit. Aenean varius. Maecenas in magna nec justo ornare feugiat. Mauris elit. Nunc</span> volutpat lectus fermentum nibh.</p>
			</div>
		</div>
		<div class="part" id="chapter-metadata-tests">
			<h3 class="part-number">2</h3>
			<h1>Chapter Metadata Tests</h1>
		</div>
		<div class="chapter" id="test-chapter-with-subtitle">
			<h3 class="chapter-number">4</h3>
			<h2>Test Chapter with Subtitle</h2>
			<div class="ugc">
				<h2 class="chapter-subtitle">A lovely way to be</h2>
				<p>In a village of La Mancha, the name of which I have no desire to call to mind, there lived not long since one of those gentlemen that keep a lance in the lance-rack, an old buckler, a lean hack, and a greyhound for coursing. An olla of rather more beef than mutton, a salad on most nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra on Sundays, made away with three-quarters of his income. The rest of it went in a doublet of fine cloth and velvet breeches and shoes to match for holidays, while on week-days he made a brave figure in his best homespun. He had in his house a housekeeper past forty, a niece under twenty, and a lad for the field and market-place, who used to saddle the hack as well as handle the bill-hook. The age of this gentleman of ours was bordering on fifty; he was of a hardy habit, spare, gaunt-featured, a very early riser and a great sportsman. They will have it his surname was Quixada or Quesada (for here there is some difference of opinion among the authors who write on the subject), although from reasonable conjectures it seems plain that he was called Quexana. This, however, is of but little importance to our tale; it will be enough not to stray a hair&#8217;s breadth from the truth in the telling of it.</p>
				<p>You must know, then, that the above-named gentleman whenever he was at leisure (which was mostly all the year round) gave himself up to reading books of chivalry with such ardour and avidity that he almost entirely neglected the pursuit of his field-sports, and even the management of his property; and to such a pitch did his eagerness and infatuation go that he sold many an acre of tillageland to buy books of chivalry to read, and brought home as many of them as he could get. But of all there were none he liked so well as those of the famous Feliciano de Silva&#8217;s composition, for their lucidity of style and complicated conceits were as pearls in his sight, particularly when in his reading he came upon courtships and cartels, where he often found passages like &#8220;the reason of the unreason with which my reason is afflicted so weakens my reason that with reason I murmur at your beauty;&#8221; or again, &#8220;the high heavens, that of your divinity divinely fortify you with the stars, render you deserving of the desert your greatness deserves.&#8221; Over conceits of this sort the poor gentleman lost his wits, and used to lie awake striving to understand them and worm the meaning out of them; what Aristotle himself could not have made out or extracted had he come to life again for that special purpose. He was not at all easy about the wounds which Don Belianis gave and took, because it seemed to him that, great as were the surgeons who had cured him, he must have had his face and body covered all over with seams and scars. He commended, however, the author&#8217;s way of ending his book with the promise of that interminable adventure, and many a time was he tempted to take up his pen and finish it properly as is there proposed, which no doubt he would have done, and made a successful piece of work of it too, had not greater and more absorbing thoughts prevented him.</p>
			</div>
		</div>
		<p>[...]</p>
		<div class="part" id="foobar">
			<h3 class="part-number">36</h3>
			<h1>Foobar</h1>
		</div>
		<p>[...]</p>
</body>
</html>


I'm running:

prince --javascript -i html file.html -o test.pdf


I get:

prince: file.html:12: error: TypeError: value is not an object


Help?
mikeday
Prince doesn't support querySelectorAll yet. You may be able to use jQuery, or the Sizzle selector library directly, or you can just call getElementsByTagName and then check the className property manually. Sorry for the inconvenience!
conner_bw
Thanks, this works:

var roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
var decimal = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];

function decimalToRoman(value) {
	if (value <= 0 || value >= 4000) return value;
	var romanNumeral = "";
	for (var i = 0; i < roman.length; i++) {
		while (value >= decimal[i]) {
			value -= decimal[i];
			romanNumeral += roman[i];
		}
	}
	return romanNumeral;
}

function romanizePartNumbers() {
	var list = document.getElementsByTagName("h3");
	for (var i = 0; i < list.length; i++) {
		if (list[i].className == "part-number") {
			list[i].innerHTML = decimalToRoman(parseInt(list[i].innerHTML));
		}
	}
}

function main() {
	romanizePartNumbers();
}

window.onload = main;


Regards,
mikeday
The querySelectorAll method is now supported in Prince 10. :)