Cannot Access Canvas Element Inside Custom Polymer Element Using Javascript

I play with the Polymer-Project web component library from Google. I want to create a custom tag with the canvas element enabled and access it from the user element through javascript. but I just can't access it using document.querySelector or document.getElementById - any hint or experience with a similar problem is appreciated.

Here is my source:

<polymer-element name="sprite-canvas"> <template> <style> .leinwand { width:200px; height:200px; background-color: lightblue; } </style> <canvas class="leinwand" width="200" height="200"></canvas> </template> <script> Polymer('sprite-canvas', { leinwand : null, ready: function() { console.log(document.getElementsByTagName('canvas')); console.log(document.querySelector('.leinwand')); }, domReady: function() { console.log(document.getElementsByTagName('canvas')); console.log(document.querySelector('.leinwand')); }, detached: function() { }, }); </script> 

The output of console.log always returns a NULL / empty collection, it does not matter in which part of the life cycle I am trying to invoke the canvas. Where is my mistake and what am I doing wrong?

Regards, Lupo

+8
javascript html5-canvas canvas polymer shadow-dom
source share
2 answers

document.getElementsByTagName('canvas') and document.querySelector('.leinwand') look for nodes in the main document. You want to query inside your shadow dom element:

 <canvas id="c" class="leinwand" width="200" height="200"></canvas> console.log(this.$.c); console.log(this.shadowRoot.querySelector('.leinwand')); 

I am using Polymer automatic node search for the first example. The second shows how you can use this.shadowRoot for the "scope" qS / qSA inside the shadow dom.

Demo: http://jsbin.com/bogorose/1/edit

+11
source share

It seems that this has changed since 2014, for polymer 1.0 I used

 console.log(this.$$('.leinwand')); 

See here for more details: https://www.polymer-project.org/1.0/docs/devguide/local-dom

+2
source share

All Articles