Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't find element inside template with querySelector - Polymer

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'.

like image 847
InvisibleUn1corn Avatar asked Dec 15 '22 19:12

InvisibleUn1corn


1 Answers

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>
like image 58
robdodson Avatar answered Dec 28 '22 22:12

robdodson