Simon Ferndriger Simon Ferndriger - 1 year ago 84
HTML Question

How to select elements from <template> with jQuery

I have two similar selections. The first uses a

tag, which works fine, the second uses a newly
tag, which doesn't work anymore.

Can anyone tell me how to get this to work with jQuery using the


<div id="div">

<template id="template">


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)

Answer Source

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:

var tc = $('#template')[0].outerHTML;

$template = $($.parseXML(tc)).contents();


Both logs return as we'd expect, and $template can now be treated as an ordinary jQuery object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download