admin管理员组文章数量:1425855
I'm making a web ponent that will show "Hello {name}!" where {name}
es from name="foo"
. When I try it I don't get any errors but it just displays "Hello null!".
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./script.js"></script>
</head>
<body>
<hello-world name="Joe"></hello-world>
</body>
</html>
script.js:
class HelloWorld extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
const p = document.createElement('p');
p.innerHTML = `Hello ${this.getAttribute('name')}!`;
this.shadowRoot.append(p);
}
}
customElements.define('hello-world', HelloWorld);
In any situation lets assume that name
will always have an input.
I'm making a web ponent that will show "Hello {name}!" where {name}
es from name="foo"
. When I try it I don't get any errors but it just displays "Hello null!".
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./script.js"></script>
</head>
<body>
<hello-world name="Joe"></hello-world>
</body>
</html>
script.js:
class HelloWorld extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
const p = document.createElement('p');
p.innerHTML = `Hello ${this.getAttribute('name')}!`;
this.shadowRoot.append(p);
}
}
customElements.define('hello-world', HelloWorld);
In any situation lets assume that name
will always have an input.
-
nvm fixed with
<script defer src="./script.js">
– TacoSnack Commented Dec 2, 2021 at 14:31 -
1
That is a hack, your are making the JS execute after all DOM is parsed. Don't do DOM access in the
constructor
like connexo explains. – Danny '365CSI' Engelman Commented Dec 2, 2021 at 15:33 -
@Danny'365CSI'Engelman Strictly speaking, access its own attributes is not accessing the DOM; the reason not to do this is that in the dynamic creation case
new HelloWorld
ordocument.createElement('hello-world')
the attribute won't be present. Relying on attributes in the constructor can easily make the element dysfunctional for those use-cases, even though in this specific case it won't even throw an error. – connexo Commented Dec 2, 2021 at 15:36
1 Answer
Reset to default 6You must not read attributes in the constructor
, otherwise you're violating the specification:
The element's attributes and children must not be inspected, as in the non-upgrade case none will be present, and relying on upgrades makes the element less usable.
From:https://html.spec.whatwg/multipage/custom-elements.html#custom-element-conformance
You must delay this kind of work until the connectedCallback
triggers, or, in the case of attributes, configure a proper attributeChangedCallback
.
Conforming to the spec will also solve your initial issue, and it will greatly enhance the functionality and usefulness of your web ponent.
Please note that it's also not the smartest of ideas to pick an attribute name that already exists in the HTML specification, as a universal attribute.
class HelloWorld extends HTMLElement {
p = document.createElement('p');
constructor() {
super();
this.attachShadow({ mode: 'open' }).append(this.p);
}
static get observedAttributes() { return ['greeting-name']; }
attributeChangedCallback(attr, oldVal, newVal) {
if (oldVal === newVal) return; // nothing to do
switch (attr) {
case 'greeting-name':
this.p.textContent = `Hello ${newVal || 'world'}!`;
break;
}
}
connectedCallback() {
if (!this.getAttribute('greeting-name')) { this.setAttribute('greeting-name', 'world'); }
}
}
customElements.define('hello-world', HelloWorld);
<hello-world greeting-name="Joe"></hello-world>
<hello-world id="foo"></hello-world>
<input type="text" oninput="document.getElementById('foo').setAttribute('greeting-name', this.value)" placeholder="Type a name" />
本文标签: javascriptthisgetAttribute not working in web component while violating the specStack Overflow
版权声明:本文标题:javascript - this.getAttribute not working in web component while violating the spec - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745391552a2656619.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论