【问题标题】:How to access the next sibling of the custom element from within the class?如何从类中访问自定义元素的下一个兄弟?
【发布时间】:2017-08-19 13:46:38
【问题描述】:
在 Web 组件中,我有一个自定义元素,我想访问下一个同级元素。我怎样才能做到这一点?我有这个
class DomElement extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({mode: 'open'});
const t = document.currentScript.ownerDocument.querySelector('#x-foo-from-template');
const instance = t.content.cloneNode(true);
shadowRoot.appendChild(instance);
}
fixContentTop() {
var sibling = this.nextElementSibling;
if (sibling) {
}
}
}
但是sibling 变为空。
有人知道怎么做吗?
谢谢
【问题讨论】:
标签:
javascript
dom
web-component
html5-template
【解决方案1】:
实际上在调用this.nextElementSibling的方法中是有效的,this真正代表了有兄弟的自定义元素。
它在本例中有效,因为借助箭头功能,this 指的是自定义元素:
customElements.define('dom-elem', class extends HTMLElement {
constructor() {
super()
var sh = this.attachShadow({mode: 'open'})
sh.appendChild(document.querySelector('template').content.cloneNode(true))
sh.querySelector('button').onclick = () =>
console.log('sibling = %s', this.nextElementSibling.localName)
}
})
<dom-elem></dom-elem>
<dom-elem></dom-elem>
<template>
<button>Get Sibling</button>
</template>
如果您使用function () 语法,这将引用<button>,因此不会返回任何同级元素:
customElements.define('dom-elem', class extends HTMLElement {
constructor() {
super()
var sh = this.attachShadow({mode: 'open'})
sh.appendChild(document.querySelector('template').content.cloneNode(true))
sh.querySelector('button').onclick = function () {
console.log('sibling = %s', this.nextElementSibling)
}
}
})
<dom-elem></dom-elem>
<dom-elem></dom-elem>
<template>
<button>Get Sibling</button>
</template>