Element for <slot>?

Is it possible to not pass a wrapper element to a <slot />? It looks like I have to use a wrapper element, otherwise I couldnt define the slot attribute for my child.
<my-custom-element>
<fragment slot="title">Hello</fragment>
</my-custom-element>
<my-custom-element>
<fragment slot="title">Hello</fragment>
</my-custom-element>
Is there something like a fragment element?
7 Replies
reddogg476
reddogg476•9mo ago
Do you have example markup and/or js?
Wonderbear
WonderbearOP•9mo ago
https://jsfiddle.net/hndqb12s/1/ Here I must use a wrapping element (<div>) to apple the title to the slot. Now the html structure is
h1 -> div -> TextNode('Hello')
h1 -> div -> TextNode('Hello')
But I want its like
h1 -> TextMpde('Hello')
h1 -> TextMpde('Hello')
Edit fiddle - JSFiddle - Code Playground
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
reddogg476
reddogg476•9mo ago
appending children is pretty easy. I see the issue now, you don't want a div element in the shadow dom. It looks like it needs some element container to be there at all, see this:
class MyExample extends HTMLElement {
constructor() {
super();

this.shadow = this.attachShadow({mode: 'open'});

this.shadow.innerHTML = `
<h1><slot name="title" /></h1>
`;
}
}
customElements.define('my-example', MyExample);

let elementContainer = document.querySelector("my-example div");
let COMMENT = document.createElement("div")
COMMENT.innerText = "Hello Two";
elementContainer.append(COMMENT);
elementContainer.innerHTML = elementContainer;
class MyExample extends HTMLElement {
constructor() {
super();

this.shadow = this.attachShadow({mode: 'open'});

this.shadow.innerHTML = `
<h1><slot name="title" /></h1>
`;
}
}
customElements.define('my-example', MyExample);

let elementContainer = document.querySelector("my-example div");
let COMMENT = document.createElement("div")
COMMENT.innerText = "Hello Two";
elementContainer.append(COMMENT);
elementContainer.innerHTML = elementContainer;
I added a new element to the slot without issue. Then I tried to reassign the slot, but the custom element doesn't redefine at the last line
reddogg476
reddogg476•9mo ago
No description
reddogg476
reddogg476•9mo ago
comment out the last line because i broke it, then the elements are added in. the wrapper is defined in the custom element, though
Aoi
Aoi•9mo ago
It is not recommended to use innerHtml with user generated content. This can lead to XSS vulnerability.
reddogg476
reddogg476•9mo ago
that's a good catch, Aoi. I'm vulnerable to cross site scripting here because I used it in a global scope. --> the comment out will fix that 😄
Want results from more Discord servers?
Add your server