cloning templates with ids

11 views
Skip to first unread message

luserdroog

unread,
Aug 7, 2023, 12:17:58 PMAug 7
to
Is there a simpler gymnastics to set the id on an element
in a document fragment, just before you append it into the
DOM? I got this working but it feels heavy handed. Would some
wild object decomposition/comprehension let me set the inner
id and return the outer fragment in a one-liner?

<html>
<body>
<template id="clickbox">
<click-box cycle
states="empty checkmark xmark questionmark"
empty=""
checkmark="&check;"
xmark="&#x2716;"
questionmark="?"></click-box>
</template>
</body>
<script src="click.js"></script>
<script>
var clickbox = document.querySelector("#clickbox");
var box1 = clickbox.content.cloneNode( true );
box1.querySelector("click-box").id = "box1";
var box2 = clickbox.content.cloneNode( true );
box2.querySelector("click-box").id = "box2";
var box3 = clickbox.content.cloneNode( true );
box3.querySelector("click-box").id = "box3";
document.body.appendChild( box1 );
document.body.appendChild( box2 );
document.body.appendChild( box3 );
document.querySelector("#box3").shadowRoot.querySelector("#box").click();
console.log( box3.value );
console.log( document.querySelector("#box3").value );
</script>
</html>

luserdroog

unread,
Aug 7, 2023, 12:23:10 PMAug 7
to
On Monday, August 7, 2023 at 11:17:58 AM UTC-5, luserdroog wrote:
> Is there a simpler gymnastics to set the id on an element
> in a document fragment, just before you append it into the
> DOM? I got this working but it feels heavy handed. Would some
> wild object decomposition/comprehension let me set the inner
> id and return the outer fragment in a one-liner?
>

Oops. Sorry for the fuss. That's what a function is for. duh.


<html>
<body>
<template id="clickbox">
<click-box cycle
states="empty checkmark xmark questionmark"
empty=""
checkmark="&check;"
xmark="&#x2716;"
questionmark="?"></click-box>
</template>
</body>
<script src="click.js"></script>
<script>
function newbox( id ){
let box = clickbox.content.cloneNode( true );
box.querySelector("click-box").id = id;
return box;
}
var clickbox = document.querySelector("#clickbox");
var box1 = newbox( "box1" );
var box2 = newbox( "box2" );
var box3 = newbox( "box3" );
Reply all
Reply to author
Forward
0 new messages