Can't find element inside template with querySelector - Polymer

╄→гoц情女王★ 提交于 2020-01-15 07:33:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!