这是Removing <span> tag while leaving content intact, with just javascript的后续问题

如果我使用跨度突出显示页面中的文本,则会将内容分解为新的节点。然后,当我使用replaceChild删除高光跨度时,节点保持分离。我想将原始文本合并回一个文本节点,而不是三个文本节点-突出显示之前的文本,先前突出显示的文本和突出显示结束的文本。这可能吗?

最佳答案

与Jim的建议类似,但适用于IE:

containerElement.innerHTML = containerElement.textContent || containerElement.innerText;


或更长的版本:

var text = containerElement.textContent || containerElement.innerText;

while (containerElement.firstChild) {
    containerElement.removeChild(containerElement.firstChild);
}
containerElement.appendChild(document.createTextNode(text));


我认为第一个比较简单。

10-05 20:36