Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymer document.querySelector not working as expected

Tags:

polymer

Either I am doing something horribly wrong or Polymer just doesn't like me. See following:

<polymer-element name="menu-paper-ui" noscript>
 <template>
  <paper-dialog heading="Dialog" transition="paper-dialog-transition-bottom">
  [ .. ]
  </paper-dialog>
  <paper-button label="Dialog Bottom" on-tap="{{toggleDialog}}"></paper-button>

 </template>
 <script>
  Polymer('menu-paper-ui', { 
    toggleDialog : function() {
      var dialog = document.querySelector('paper-dialog');
      console.log(dialog); //returns null
      dialog.toggle();
    }
  })

 </script>
</polymer-element>

Now, I have my reasons to use querySelector. So, if someone can tell me whats going wrong that will be great!

like image 508
Vikas Singhal Avatar asked Dec 07 '22 01:12

Vikas Singhal


2 Answers

This question is nearly identical to Using querySelector to find nested elements inside a Polymer template returns null.

The short answer is that elements in a polymer-element's template are put into the ShadowDOM of that element, are not not visible to the anything outside of that element. This is so that you can control styling more easily, and element IDs are scoped.

You can either give the dialog an id and use Polymer's automatic node finding, or use this.shadowRoot.querySelector('paper-dialog').

like image 122
dfreedm Avatar answered Feb 12 '23 18:02

dfreedm


The Problem is that you can not access the shadow DOM inside a custom element with document.querySelector. See my answer to a similar question.

like image 28
Dirk Grappendorf Avatar answered Feb 12 '23 17:02

Dirk Grappendorf