Search code examples
javascriptpolymerpolymer-1.0web-component

Appending DOM element to local dom does not apply styles


Within my Polymer (v1.2.3) element, I need to dynamically append newly created DOM elements to certain local DOM nodes. The elements I am appending contain a class="foo", where class foo has styles scoped within my polymer element.

The problem I am facing is that these styles are not applied to the elements.

The following code will exemplify the issue:

  attached: function () {
    var el = document.createElement("span");
    el.textContent = "Woof. Woof. Meow!";
    el.classList.add("foo");

    Polymer.dom(this.root).querySelector(".bar").appendChild(el);
  }

Here is my template:

<dom-module id="my-element">
<template>

<style>
   .foo {
        color: red; 
  }
</style>
<div class="bar"></div>
<div class="baz"><span class="foo">I am not added dynamically!</span></div>

</template>
...
</dom-module>

In the above template, the element .foo within .baz will have styles applied to it but, element .foo within .bar would not (polymer's class style-scope is no applied to it).

Some additional info:

  • style-scope not added to dynamically created elements.
  • Polymer.dom(this.root).appendChild(el) applies styling but, does not add it at desired location.
  • Calling updateStyles() or Polymer.dom.flush() explicitly after the element is added, does not resolve the issue.
  • Polymer version 1.2.2 also contains this issue

Solution

  • There is an open bug that requires to append :host:: content as a prefix to each style.