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

584 Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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.

1
On

This might be a bug with Chrome, have you also tried it in Firefox with the web components flag turned on?

More importantly, this method of selecting elements is going away in favor of a "named slots" method. I don't know if it has hit any browsers yet though. It might not be worth much trouble to fix this problem.

0
On

I think this is because one of the anchor tags is not a direct child of the div element you have it in.