Reputation: 179
I'm trying to learn Polymer 2.0 but am stuck with the problem of getting an element from a different Shadow Dom. This worked in Polymer 1 but no longer in Polymer 2.0. What is the correct way of writing this? It just tells me that the targetText = Null
.
Thanks for your help!
This is a MWE: Polymer WC 1:
<dom-module id="sc-navdrawer">
<template>
<style is="custom-style">
p {
font-weight: bold;
}
.changed {
color: red;
}
</style>
<p>Some text in normal p tag</p>
<div id="test" class="htmltextcontent" inner-h-t-m-l="{{inputText}}"></div>
</template>
<script>
Polymer({
is: 'sc-navdrawer',
properties: {
inputText: {
type: String,
value: "<p>Some innerhtml text in p tags</p>"
}
}
});
</script>
</dom-module>
Polymer WC 2:
<dom-module id="sc-testpage">
<template>
<button onclick="{{changeColor}}">Click here to change color</button>
</template>
<script>
Polymer({
is: 'sc-testpage',
changeColor: function() {
var targetText = document.getElementById("test");
console.log(targetText);
targetText.classList.add("changed");
}
});
</script>
</dom-module>
Upvotes: 4
Views: 6436
Reputation: 1259
Well first thing that I see is you use document.getElementById("test");
and if you say this worked you have used Shady Dom.
Polymer 2 forces you to use Shadow Dom so this command should be replaced by Polymer.dom(this.root).querySelector("#test")
. Because Shadow Dom encapsulates your Component you cant access its content with the document
Object
But this should not fix your Problem. This Encapsulation means you can´t access the Content of a WebComponent so you cannot access an element with id:xyz from another Component. Have a look at these links they will explain to you how shadowDom works:
1. https://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/
2. https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM
3. https://glazkov.com/2011/01/14/what-the-heck-is-shadow-dom/
Upvotes: 4
Reputation: 1309
Further on, I do not really understand why you are using two way data binding on your onclick attribute. I might be missing something but your code should work perfectly fine with a normal function call.
<dom-module id="sc-testpage">
<template>
<button on-tap="changeColor">Click here to change color</button>
</template>
<script>
Polymer({
is: 'sc-testpage',
changeColor: function() {
var targetText = this.$.sc-navdrawer.$.test;
console.log(targetText);
targetText.classList.add("changed");
}
});
</script>
</dom-module>
Upvotes: 0
Reputation: 225
Try using paper-input and setting it's value:
<paper-input id="test" label="input" value="{{inputText}}"></paper-input>
Then you can access the variable like this:
var targetText = this.$.inputText;
(this should work with other elements other than paper-input)
Upvotes: 0