HTML is being written by XSLT.
As an amateur XSLT developer
I want to write a javascript block into the HTML (head or body)
So that the script can be executed when the HTML is rendered (loo and behold, DHTML).
I know how to use script in the XSLT itself, but not how XSLT can write a script block to DHTML. I know how to write the HTML by hand, but of course I want the XSLT to do the heavy-lifting.
The below code is what I expected to work, but doesn't. It simply displays the code in the head of the page.
<head>
<title>My HTML</title>
<msxsl:script type="text/javascript" version="1.3">
<![CDATA[
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
]]>
</msxsl:script>
</head>
This is for NHS work, so pretty please ... thank you.
If the HTML your XSLT creates is supposed to contain a HTML
scriptelement then you would literally insert it the same way as you have used aheadortitleelement. In the XSLT, XSLT being XML, you would need to ensure your inline Javascript code doesn't break XML rules, as you have done with the CDATA section, but thescriptelement would be a plainscriptelement and not anmsxsl:scriptelement.Other than that and using
xsl:output method="html", there is not anything special.It is questionable what your particular code in the
headsection usingvar coll = document.getElementsByClassName("collapsible");and trying to process that collection is supposed to achieve before any elements are parsed but that is rather a question of the appropriate use of Javascript and perhaps an event handler or a function call instead of inline code.Depending on where your XSLT is executed (client or server), the whole interaction of XSLT and Javascript can be brittle, adding script dynamically, even without XSLT, can be a challenge cross-browser.