How to distribute (insert) content nodes programmatically

前端 未结 2 1181
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 19:18

Is there a way to programmatically distribute (insert) content from lightDOM to ShadowDOM?

I would like to wrap every single child node into an element. For example :

相关标签:
2条回答
  • 2021-02-06 19:42

    Composition is something Shadow DOM is designed for. If that spec bug gets fixed, the best way to do this would be interesting tricks with <content select=":nth-child(...)"> in a <template repeat>. Since you can't (currently) use :nth-child, you could instead use the distributed nodes and data-binding to wrap the content:

    <template repeat="{{node in nodes}}">
      <li>
        <html-echo html="{{node.outerHTML}}"></html-echo>
      </li>
    </template>
    <content id="c" select="*"></content>
    

    nodes is generated from something like:

    this.nodes = Array.prototype.slice.call(this.$.c.getDistributedNodes());
    

    I'm using <html-echo> from this post: https://stackoverflow.com/a/22208332/274673

    Working demo: http://jsbin.com/mamawugo/2/edit

    0 讨论(0)
  • 2021-02-06 19:49

    There is quite old issue at W3C Bugzilla: #18429 - [Shadow]: Specify imperative API for node distribution

    But as for now, there is nothing in spec about that.

    0 讨论(0)
提交回复
热议问题