Search code examples
javascriptjqueryhtmltemplates

How to select elements from <template> with jQuery


I have two similar selections. The first uses a <div> tag, which works fine, the second uses a newly <template> tag, which doesn't work anymore.

Can anyone tell me how to get this to work with jQuery using the <template> tag?

HTML

<div id="div">
    <div>content</div>
</div>

<template id="template">
    <div>content</div>
</template>

JavaScript

var $div = $('#div');
var $content = $div.find('div');
console.log($content); //works ($content.length == 1)

var $template = $('#template');
var $content = $template.find('div');
console.log($content); //doesn't work ($content.length == 0)

http://jsfiddle.net/s8b5w0Le/1/


Solution

  • HTMLTemplateElement saves the DOM into a separate attribute.

    jQuery

    <script src="jquery-3.1.0.js"></script>
    <script type="text/javascript">
        $(document).ready(function()
        {
            var $div = $('#div');
            var $content = $div.find('div');
            console.log($content.text()); // output "content", inner div
    
            var $template = $('#template');
            var node = $template.prop('content');
            var $content = $(node).find('div');
            console.log($content.text()); // output "content", inner template
        });
    

    JavaScript

    document.createElement('template').content