0

Edit: Just found this link, that explains it somehow. Using querySelector to find nested elements inside a Polymer template returns null

Nonetheless I'd appreciate an answer to my question on this specific code.

/Edit

I think a rather straight forward and minimalistic problem:

I've got a custom element in polymer:

 <polymer-element name="my-test">
    <template>
        <div id="content">
            <h3 id="test">My Test</h3>
            <p id="paragraph">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi dolore consectetur, mollitia eos molestias totam ea nobis voluptatibus sed placeat, sapiente, omnis repellat dolores! Nihil nostrum blanditiis quasi beatae laborum quisquam ipsum!</p>
            <button id="button">Clicke Me!</button>
        </div>

    </template>
    <script>
    Polymer('my-test', {
        ready: function() {
            var button = this.$.button;
            button.addEventListener("click", function() {
                alert("alert");
            });
        }
    });
    </script>
</polymer-element>

The thing is, that I would rather use

 var button = document.querySelector(#button);

instead of

 var button = this.$.button;

Because it seems more intuitive and declarative. But whenever I do this I get an error that says:

 "Uncaught TypeError: Cannot read property 'addEventListener' of null " in Chrome and

 Firefox instead says: "TypeError: button is null"

So any help is appreciated! :)

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
LoveAndHappiness
  • 9,735
  • 21
  • 72
  • 106

2 Answers2

6

Your button is inside your Polymer element and because Polymer elements have their content inside their shadow DOM the element can't be found this way. You can either use this.shadowRoot.querySelector('#button'); or document.querySelector('* /deep/ #button'); or document.querySelector('my-test::shadow #button'); if your <my-test> element is not within the shadow DOM of another element. /deep/ pierces through all shadow DOM boundaries ::shadow just through one.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks a lot Günter, did you get all this information out of the docs? Or can you recommend another resource? – LoveAndHappiness Nov 09 '14 at 13:59
  • I follow Polymer development closely for more than a year and constantly pick up bits of information here and there so I can't tell where I read it but the Polymer-project.com page is pretty comprehensive. – Günter Zöchbauer Nov 09 '14 at 14:59
2

Actually following line:

var button = document.querySelector(#button);

Should be:

var button = document.querySelector('#button');

Notice the quotes.

The Alpha
  • 143,660
  • 29
  • 287
  • 307