问题
When I try to querySelector an element inside a template tag from external file I get undefined, after a little bit of searching the only solution I found was the 'shadowRoot' but when I tried to use it I got 'shadowRoot is not defined'.
回答1:
The following code works fine for me (jsbin):
<template is="auto-binding" id="tmpl">
<h1>Hello from {{foo}}</h1>
</template>
<script>
document.addEventListener('polymer-ready', function() {
var tmpl = document.querySelector('#tmpl');
tmpl.foo = 'my thing';
});
</script>
I added the polymer-ready
event since it's generally a good practice to wait for all of your elements to be ready before trying to play around with them.
edit: The OP wants to know how to find an element inside a template
To locate an element inside of a template you'll need to querySelector
using the template's content
keyword. This is to prevent accidentally selecting things inside of templates (for example, if you were to query selector all p
tags on the page, you might not want a p
tag inside of a template that hasn't been stamped out yet).
Here's an example which changes an h2
inside the template
(jsbin)
<template is="auto-binding" id="tmpl">
<h1>Hello from {{foo}}</h1>
<h2>Another header</h2>
</template>
<script>
document.addEventListener('polymer-ready', function() {
var tmpl = document.querySelector('#tmpl');
tmpl.foo = 'my thing';
var h2 = tmpl.content.querySelector('h2');
h2.textContent = 'hello world';
});
</script>
来源:https://stackoverflow.com/questions/26016160/cant-find-element-inside-template-with-queryselector-polymer