I have two similar selections. The first uses a tag, which doesn\'t wor
var $content = $template.content.find('div');
... instead of ...
var $content = $template.find('div');
Worked for me.
HTMLTemplateElement saves the DOM into a seperate 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
HTML5 template is display: none;
by default, childNodes
in template is invalid, if you inspect it in console you'll find something different
As others have noted, Chrome puts <template>
child elements into a shadow DOM. To access them:
// Access the JavaScript object for the template content
$('template')[0]
// Make a jQuery selection out of it
$($('template')[0])
// Now you can search it
$($('template')[0]).find('div.someclass').css('color','#000');
I'm fairly certain this has to do with Chrome's use of shadow dom (thank Polymer... )
You can either try your luck using the /deep/
combinator (probably won't work on other browsers), but I think the most robust solution would be $template[0].outerHTML
as in your comment if you just need the text.
If you need jQuery functionality, using $.parseXML
(to avoid Chrome's native dom construction) would probably do the trick across all browsers (can confirm Chrome + FF).
Example here: http://jsfiddle.net/3fe9jjfj
var tc = $('#template')[0].outerHTML;
$template = $($.parseXML(tc)).contents();
console.log($template);
console.log($template.find('div'));
Both logs return as we'd expect, and $template
can now be treated as an ordinary jQuery object.