Динамически добавлять класс в веб-компоненты из JavaScript, используя classList
Как добавить динамические стили в теневой DOM
index.html
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<link rel="import" href="nav-component.html">
</head>
<body>
<app-nav></app-nav>
</body>
</html>
нав-component.html
<template>
<style>
.btn {
background-color: green;
padding: 10px 20px;
}
</style>
<button onclick="getstyles()">ENTER</button>
</template>
<script src="nav-component.js"></script>
нав-component.js
let template = document.currentScript.ownerDocument.querySelector('template');
let clone = document.importNode(template.content, true);
let proto = Object.create(HTMLElement.prototype);
proto.createdCallback = function () {
let root = this.createShadowRoot();
root.appendChild(clone);
}
document.registerElement('app-nav', {
prototype: proto
});
function getstyles() {
console.log('it works');
document.querySelector('button').classList.add('btn');
// document.currentScript.ownerDocument.querySelector('button').classList.add('btn');
}
должен добавить класс btn к элементу кнопки, чтобы его стили были добавлены к элементу кнопки
получена ошибка Uncaught TypeError: Невозможно прочитать свойство 'classList' с нулевым значением
2 ответа
Решение
Прежде всего document.registerElement
устарела, поэтому я ответил на решение по созданию пользовательских элементов на основе классов здесь...
Решение состоит в том, чтобы получить документ от document.currentScript.ownerDocument
class AppNavElement extends HTMLElement {
constructor() {
super()
// import from ownerDocument
const importDoc = document.currentScript.ownerDocument;
let shadowRoot = this.attachShadow({mode: 'open'});
const template = importDoc.querySelector('#template');
const instance = template.content.cloneNode(true);
shadowRoot.appendChild(instance);
// Event Listener
this.addEventListener('click', e => this.changeStyle());
}
changeStyle() {
this.shadowRoot.querySelector('button').classList.add('btn')
}
}
customElements.define('app-nav', AppNavElement)
Обновить:
Для прослушивания элемента кнопки используйте только connectedCallback
спасибо @bhv
connectedCallback() {
let btn = this.shadowRoot.querySelector('button')
// Event Listener
btn.addEventListener('click', e => this.changeStyle());
}
Вы также можете просто получить <button>
элемент из event.target
имущество:
function changeStyle() {
console.log('it works');
event.target.classList.add('btn');
}
...
<button onclick="changeStyle()">ENTER</button>