[英]Property 'id' does not exist on type 'Node' in plain JS after cloneNode
I've got a pure JS function that adds a message to the page based on a chunk of "template" HTML.我有一个纯 JS function,它根据一块“模板”HTML 向页面添加一条消息。
const setMessage = (msg, type, msg_ct) => {
const msg_text = document.createTextNode(msg)
const elementToCopy = document.querySelector('#js_message_template')
const msg_container = document.querySelector('#js_message_container')
const clone = elementToCopy.cloneNode(true)
clone.id = `js_message_alert_${msg_ct}`
clone.classList.add(`alert-${type}`)
clone.appendChild(msg_text)
msg_container.appendChild(clone);
}
VS code is complaining about clone.id
and clone.classList
as a Node cannot have those properties. VS 代码抱怨
clone.id
和clone.classList
因为 Node 不能具有这些属性。
Now every answer and tutorial I've seen about cloning a chunk of HTML like this basically says to do exactly what I'm doing.现在,我看到的每个关于克隆 HTML 块的答案和教程基本上都在说我正在做的事情。
I can also see this is a Typescript error, though as I understand it this powers the VS Code JS checks as well, so for the moment I assume it's a valid error (?)我还可以看到这是一个 Typescript 错误,尽管据我了解,这也为 VS Code JS 检查提供了动力,所以目前我认为这是一个有效错误(?)
It makes sense that a node wouldn't have an ID like this, but what is the correct way to set the ID and add a class to the outer element of this node when I am doing this?一个节点没有这样的 ID 是有道理的,但是当我这样做时,设置 ID 并将 class 添加到该节点的外部元素的正确方法是什么? Again, all googling leads me to examples that do exactly what I am doing!
再一次,所有的谷歌搜索都会让我找到完全符合我正在做的事情的例子!
You could fix it by specifying what type it is with JSDOC for example:您可以通过使用 JSDOC 指定它的类型来修复它,例如:
/** @type {HTMLElement} */
const clone = elementToCopy.cloneNode(true);
A better way would be instanceof
:更好的方法是
instanceof
:
const clone = elementToCpoy.cloneNode(true);
if (clone instanceof HTMLElement) {
...
}
I assume you are cloning an HTMLElement (an HTMLElement derives from Element, which drives from Node).我假设您正在克隆一个 HTMLElement(一个HTMLElement派生自 Element,它从 Node 驱动)。
Node doesn't have an id
attributes, but HTMLElement
(and also Element
) does. Node 没有
id
属性,但HTMLElement
(还有Element
)有。
All you have to do is tell the compiler the cloned node is something more specific than a Node
.您所要做的就是告诉编译器克隆的节点比
Node
更具体。 Eg例如
const clone = elementToCopy.cloneNode(true) as HTMLElement;
If you really want to be safe, you can explicitly check for it.如果你真的想要安全,你可以明确地检查它。 Eg:
例如:
const clone = elementToCopy.cloneNode(true)
if (clone instanceof HTMLElement) {
clone.id = `js_message_alert_${msg_ct}`
...
}
Up to you.由你决定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.