Search code examples
htmlfallbackjavafx-webenginehtml5-template

html5 template tag: fallback for content access


I am using a template tag in a webkit browser (JavaFX WebView 2.2) to store elements that I may clone and append on the main part of the document.

However, I can't access its content using templateElement.content (the HTML5 standard). Instead, I use jQuery to get the elements inside the template TAG with the selector "#templateElement div".

Seems the template tag is not yet fully supported (inner scripts also run), although its contents are not rendered.

My fear is that, when the template tag becomes supported, the way to get its contents will break and my page will stop working.

What is the recommended way of getting template contents regardless future implementation changes?

HTML:

<template id="templateElement">
    <div>Clone Me!</div>
</template>

JavaScript:

function getContentsCurrent() {
    var toBeCloned = $("#templateElement div")[0];
    //append where needed...
}

function getContentsFuture() {
    var toBeCloned = templateElement.content.getElementsByTagName("div")[0];
    //append where needed...
}

EDIT

I think jQuery won't be able to handle this automatically, even in the future, because the template "innerHTML" is purposely routed to content so that it becomes inaccessible to the DOM (so no selector touches it accidentally).


Solution

  • You could test if the content feature exists before:

    function getContents() {
      var toBeCloned;
      if ( templateElement.content )
        toBeCloned = templateElement.content.getElementsByTagName("div")[0];
      else
        toBeCloned = templateElement.querySelector("div");
      //append where needed...
    }
    

    Another way:

    var content = templateElement.content || templateElement
    var toBeCloned = content.querySelector( "div" )
    //...