[英]Web Components: how to access a slotted element using shadowRoot.querySelector
Hi I am new to Web Components concept.嗨,我是 Web 组件概念的新手。 I wanted to know if we can access a slotted element using shadowRoot.querySelector
我想知道我们是否可以使用 shadowRoot.querySelector 访问带槽的元素
I have implemented an input field as slot for setting some values dynamically.我已经实现了一个输入字段作为用于动态设置一些值的插槽。 And have a class added to it 'column-title'.
并为其添加一个类“列标题”。 I am trying to access this element in connectedCallback() like this
我正在尝试像这样在 connectedCallback() 中访问这个元素
var titleInput = this.shadowRoot.querySelector('.column-title')
But it returns null.但它返回空值。
Please help.请帮忙。
I'm not sure what the issue is, but you should be able to get a slot using querySelector
and its class.我不确定问题是什么,但是您应该能够使用
querySelector
及其类获得一个插槽。 I've mocked up an example below.我在下面模拟了一个例子。
The console will print out references to the slot.控制台将打印出对插槽的引用。 If you're attaching a class just for the purpose of finding the slot then it's probably better to set an id (assuming that it's within a shadow root) and find it with
this.shadowRoot.getElementById('my-slot-id')
如果您附加一个类只是为了找到插槽,那么最好设置一个 id(假设它在影子根中)并使用
this.shadowRoot.getElementById('my-slot-id')
找到它
customElements.define('blue-box', class extends HTMLElement { constructor() { super(); var template = document .getElementById('blue-box') .content; const shadowRoot = this.attachShadow({ mode: 'open' }) .appendChild(template.cloneNode(true)); } connectedCallback() { console.log(this.shadowRoot.querySelector('slot.target-slot')); } });
<template id="blue-box"> <style> .blue-border { border: 2px solid blue; padding: 5px; margin: 5px; } </style> <div class='blue-border'> <slot name='interior' class='target-slot'>NEED INTERIOR</slot> </div> </template> <blue-box> <span slot='interior'>My interior text</span> </blue-box> <blue-box> <span slot='interior'> Check Here: <input type='checkbox'> </span> </blue-box>
Going off of @royyko 's response.离开@royyko 的回应。 The better answer here is instead of giving a class or id with the purpose to grab the slot... use the already provided identifier, its name.
这里更好的答案是,而不是提供一个类或 id 以获取插槽......使用已经提供的标识符,它的名称。 To do this you would do the following
this.shadowRoot.querySelector('slot[name=interior]')
为此,您将执行以下操作
this.shadowRoot.querySelector('slot[name=interior]')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.