Polymer: Using querySelector on custom element instead of "this. $."
Edit: Just found this link which explains it somehow. Using querySelector to find nested elements inside a Polymer template returns null
However, I would appreciate an answer to my question on this particular code.
/ Edit
I am thinking of a rather straight forward and minimalistic problem:
I have my own 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, I would rather use
var button = document.querySelector(#button);
instead
var button = this.$.button;
Because it seems more intuitive and declarative. But whenever I do this, I get the error:
"Uncaught TypeError: Cannot read property 'addEventListener' of null " in Chrome and Firefox instead says: "TypeError: button is null"
So any help is appreciated! :)
source to share
Your button is inside your Polymer element, and since Polymer elements have their content inside their DOM DAM, this element cannot be found this way. You can use this.shadowRoot.querySelector('#button');
either document.querySelector('* /deep/ #button');
or document.querySelector('my-test::shadow #button');
, if your element is <my-test>
not in the shadow DOM of another element. /deep/
breaks all shadow DOM borders ::shadow
through only one.
source to share