简体   繁体   中英

ShadowDOM: how do I repeat content?

So I know that, using Polymer, you can repeat content in the ShadowDOM tree by using the "repeat" attribute. But how do I do this in the native ShadowDOM spec? Is that possible?

In this example: http://css-tricks.com/modular-future-web-components/ the author uses nth-of-type function. But it works when you know how many times an element from the actual DOM is going to be repeated (4 in this case). What I would like to achieve is to be able to handle indefinite number of repetitions.

This is pretty straightforward. Once you use a template, it's gone. So to repeat content, you'd just need to update the template with the content you want, and then make a clone of it, and use the clone that you just created.

JSFiddle Example

 if ('content' in document.createElement('template')) { var target = document.querySelector('.content-container'), aside = target.content.querySelectorAll("aside"); aside[0].textContent = "Shadow DOM Content"; aside[1].textContent = "More Shadow DOM Content"; aside[2].textContent = "Even More Content!"; // Clone the new row and insert it into the table var section = document.getElementsByClassName("first-section") var clone = document.importNode(target.content, true); section[0].appendChild(clone); // Create a new row aside[0].textContent = "test 1"; aside[1].textContent = "test 2"; aside[2].textContent = "test 3"; // Clone the new row and insert it into the table var clone2 = document.importNode(target.content, true); section[0].appendChild(clone2); } else { // do something else }
 body { background: lightgrey; } .first-section aside { background: grey; padding: 5px; } .first-section aside:nth-child(3n) { margin-bottom: 15px; }
 <div> <div class="first-section"> A repeated use of template: <div> </div> <template class="content-container"> <aside></aside> <aside></aside> <aside></aside> </template>

Using this method, you can re-use your template as many times as you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM