Search code examples
htmlgoogle-chromeweb-componentshadow-domcontent-tag

How to select nested elements with <content select="">


In Chrome 44 I'm trying to create a shadow DOM that renders a specific set of children of the shadow host.
In the following code, the <content select="a"> part is selecting only two of the three <a> elements.

<div id=a>
    <a>1</a>
    <span><a>2</a></span>
    <a>3</a>
</div>

<template id=b>
    <content select="a"></content>
</template>

<script>
shRoot = document.getElementById('a').createShadowRoot() ;
shRoot.appendChild( document.importNode(document.getElementById('b').content, true) ) ;
</script>

How can I select all the elements I want, no matter if they are nested or not?
Is there a restriction as to what kind of elements are selectable?


Solution

  • This is not a bug in implementation of content tag, this is indeed how it works.

    As explained here in HTML5Rocks article on shadow dom 101:

    Note: select can only select elements which are immediate children of the host node. That is, you cannot select descendants (e.g.select="table tr").

    Therefore, content selectors by implementation only target immediate children, not nested elements.