1

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 changed content. How to fix that? Here's the part of the code of a custom element created with Polymer:

Polymer({
  attached: function() { 
    this.querySelector(".post-body").innerHTML = this.format(this.querySelector(".post-body").innerHTML);
  },
  format: function(text) { 
    return text.replace(/\n(.+)\n/g, "<p>$1</p>");
  },
});

In this example I get the right formatting but my stylesheet styles don't apply to the P element inside it. Is there anyway to fix it like re-applying styles to page or anything else?

user2733016
  • 77
  • 1
  • 7
  • I suggest you to look at this question/answer http://stackoverflow.com/questions/13075920/add-css-rule-via-jquery-for-future-created-elements – Kristijan Iliev Jun 23 '15 at 10:45

2 Answers2

2

After updating the HTML call this.updateStyles().

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

Zikes
  • 5,888
  • 1
  • 30
  • 44
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();.

Community
  • 1
  • 1
Aaron St Clair
  • 128
  • 2
  • 9