LoveAndHappiness
LoveAndHappiness

Reputation: 10135

Polymer: Using querySelector in Custom Element instead of "this.$."

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! :)

Upvotes: 0

Views: 3831

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657118

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.

Upvotes: 6

The Alpha
The Alpha

Reputation: 146191

Actually following line:

var button = document.querySelector(#button);

Should be:

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

Notice the quotes.

Upvotes: 2

Related Questions