gpt4 book ai didi

javascript - 元素内部的自定义 div 不保留属性

转载 作者:行者123 更新时间:2023-11-30 09:11:47 25 4
gpt4 key购买 nike

所以我有这段代码:

const div = (tag) => {
const ptag = document.querySelector(tag);
const shadow = ptag.attachShadow({
mode: 'closed'
});
const div = document.createElement('div');
div.textContent = ptag.textContent;
shadow.appendChild(div);
}
div('foo-bar')
<foo-bar>
<h1>Hi</h1>
</foo-bar>
我希望“嗨”会出现在通常的 h1 标签样式中,但这里没有。大概是什么原因。

感谢修复。在此先感谢合作伙伴。非常感谢制作custags.js .

最佳答案

关于您正在使用的 div.textContent,这只会获取内容字符串,而不是整个 HTML。

引用MDN

The textContent property of the Node interface represents the text content of the node and its descendants.

Element.innerHTML returns HTML, as its name indicates. Sometimes people use innerHTML to retrieve or write text inside an element, but textContent has better performance because its value is not parsed as HTML. Moreover, using textContent can prevent XSS attacks.

更多关于 Node.textContent .

在这种情况下,最好使用 innerHTML,因为您想在此处保留 foo-bar 中的 h1

const div = (tag) => {
const ptag = document.querySelector(tag);
const shadow = ptag.attachShadow({
mode: 'closed'
});
const div = document.createElement('div');
div.innerHTML = ptag.innerHTML;
shadow.appendChild(div);
}
div('foo-bar')
<foo-bar>
<h1>Hi</h1>
</foo-bar>

关于javascript - 元素内部的自定义 div 不保留属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58183880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com