Forum How do I...?

Replacing text with JavaScript

pronik
I guess I don't get how this works...

I'm trying to fetch text from a <title> tag and put its contents into a <h1> on my front page. Trying to do as the examples have shown me:

...
<script type="text/javascript">
  function init_prince() {
  var target = document.createElement("h1");
  var source = document.getElementsByTagName("title")[1];
  target.textContent = source.textContent;
  var page = document.getElementById("front-page");
  page.insertBefore(target, page.firstChild);
  }
</script>

  </head>

  <body onload="init_prince();">
...


This works in a browser, but doesn't in Prince. Any ideas what I could be missing? And while we are at it: is Prince 8.0 coming out soon? ;)
mikeday
Prince 8.0 will be coming out real soon, and we're already planning 8.1 based on early feedback.

Your example should not work in a browser, unless you change it to getElementsByTagName("title")[0] to select the first title element, remembering that JavaScript arrays start indexing from zero. :)

The other reason it doesn't work in Prince is that we don't support the textContent property. Perhaps we can add this in Prince 8.1. For now there is this workaround:
target.appendChild(document.createTextNode(source.firstChild.nodeValue));

Not quite as pretty, maybe? :)
pronik
mikeday wrote:
Your example should not work in a browser, unless you change it to getElementsByTagName("title")[0] to select the first title element, remembering that JavaScript arrays start indexing from zero. :)


Well it does -- I haven't said that my markup is valid ;) Due to several templating hickups, I actually have two <title>s -- will be corrected soon, obviously.

mikeday wrote:
The other reason it doesn't work in Prince is that we don't support the textContent property. Perhaps we can add this in Prince 8.1. For now there is this workaround:
target.appendChild(document.createTextNode(source.firstChild.nodeValue));

Not quite as pretty, maybe? :)


Excellent, I take working ugly code instead of non-working piece of art anytime :) Thanks!
mikeday
Prince 8.1 is now available for download, and it supports the textContent property and numerous other JavaScript DOM improvements.