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

Custom div inside elements don't retain properties

所以我有这个代码:

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>
我预计 'Hi' 会出现在通常的 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>