Skip to content Skip to sidebar Skip to footer

Applying Styles To Elements Inserted With Innerhtml In Polymer

I have some element that contains content of element in it and I want to format it and the only way that worked is changing InnerHTML. However, local stylesheet doesn't apply to ch

Solution 1:

After updating the HTML call this.updateStyles().

https://www.polymer-project.org/1.0/docs/devguide/styling.html#style-api

Solution 2:

st_efan seems to have hit the nail on the had in another thread: https://stackoverflow.com/a/32306440

His solution is to use the native Polymer DOM API to achieve this.

I was having the same issue as you describe: I could get my data to stamp, however it would never get styled. Calling this.updateStyles() didn't resolve my issue, as it appeared the method I was using to stamp was not applying the innerHTML in a Polymeric method.

In my examples I am using the following CSS for styling:

p {
    font-weight: bold;
    color: red;
}

In your original post, you are using the Polymer DOM API. However, for anyone else reading, it is not so obvious. The data stamps as expected using the following:

var html = "<p>This is a test</p>";
this.$.myElementId.innerHTML = html;

However, using this method will never allow the CSS styling applied to a polymer element to take effect in the innerHTML. The method suggested by Zikes should work in some contexts, however I believe it only applies custom properties set via host and mixins. The following does not work in my testing.

var html = "<p>This is a test</p>";
this.querySelector("#myElementId").innerHTML = html;
this.updateStyles();

The solution that does end up working in my testing, and seems very much to be the appropriate method of setting the innerHTML is via Polymer.dom:

var html = "<p>This is a test</p>";
Polymer.dom(this.$.myElementId).innerHTML = html;

In this final example, there is no need to call this.updateStyles();.

Post a Comment for "Applying Styles To Elements Inserted With Innerhtml In Polymer"