EliteKnight
EliteKnight

Reputation: 87

Append XSL tags to HTML DOM elements

If I have an empty XSL doc as follows:

<body>
   <div id="myList">

   </div>
</body>

How can I access the div tag and append XSL to it? For example, I want to do the following in my js code but it doesn't output anything. But if I manually insert the innerHTML value into the div tag it works:

document.getElementById("myList").innerHTML = `<xsl:value-of select="Movies/Authors/FirstName"/>`

I've tried using different quote styles but I can't seem to get the expected output. Is there any way around this?

Upvotes: 0

Views: 214

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167506

Assuming you have an XSLT stylesheet as an XML DOM document and a recent version of a browser supporting innerHTML on XML elements (I have tested successfully with current versions of Chrome, Firefox and Edge on Windows 10 Creators Update) you can use e.g.

var xslString = `<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="Root">
   <div id="myList">

   </div>  
  </xsl:template>

</xsl:stylesheet>`;

var xmlString = `<Root>
  <Movies>
     <Authors>
       <FirstName>Steven</FirstName>
     </Authors>
  </Movies>
</Root>`;

var domParser = new DOMParser();

var xsltDoc = domParser.parseFromString(xslString, 'application/xml');

var xmlDoc = domParser.parseFromString(xmlString, 'application/xml');

var div = xsltDoc.querySelector('#myList');

div.innerHTML = `<xsl:value-of select="Movies/Authors/FirstName"/>`;

var proc = new XSLTProcessor();
proc.importStylesheet(xsltDoc);

document.getElementById('result').appendChild(proc.transformToFragment(xmlDoc, document));
<section>
  <h1>Result</h1>
  <div id="result"></div>
</section>
  

Upvotes: 1

Related Questions