const div = document.getElementById('my_example_id'); // get the node
const html = div.outerHTML.replace(div.innerHTML || '', ''); // simple set logic
console.log(html);
只是一些方法来做到这一点,而不是说最好的。
const div = document.getElementById('my_example_id');
const copy = div.cloneNode(true);
const parent = document.createElement('div');
copy.innerHTML = '';
parent.appendChild(copy); // I forgot to add this line.
const html = parent.innerHTML;
console.log(html);
基本上,您创建 div 的副本,创建父级,然后删除复制节点的 innerHTML 以仅保留“div”本身。将复制的节点附加到新的父节点并显示父节点的innerHTML,这正是您想要的“div”。