9
votes

I'm trying to access to a part of my component by querySelector, but it return null.

My html in my component looks like :

<nav class="mainmenu">
   <div class="container">
       <div class="dropdown" id="my-dropdown">

The reason I want to access this, is because, I want to change classes in certains conditions when user click somewhere in body.

void ready(){
 document.body.onClick.listen((E)  {
   if(_isActive){
    querySelector("#my-dropdown");

the querySelector always retun null. Why ?

I understand shadow dom forgive me to access in other dom component, but why in the same component ? How can I access to it ? Or maybe I should process differently ?

1
Try shadowRoot.querySelector('#my-dropdown'). This means querySelector will select the element within the shadow dom of your element, not the publicly visible dom which is what this.querySelector() does. - Greg Lowe
You can also use this writing to select by id within a PolymerElement: var dropdown = $['my-dropdown']; - Anthony Bobenrieth

1 Answers

16
votes

When you use querySelector("#my-dropdown") you are using the top level function querySelector. This function search in the main document and not inside the ShadowDOMs of the polymer elements.

In your case you should use shadowRoot.querySelector('#my-dropdown') or $['my-dropdown'] (it's a shortcut) to get the element you are querying.