我看不出我做错了什么:
var html = existingSelector.innerHTML;
var node = document.createTextNode(html);
existingSelector.parentNode.replaceChild(node, existingSelector);
existingSelector
是
selectedContents.querySelector("b");
正确运行代码会删除" b"元素,但不会在其位置插入新节点。它只是删除整个节点,而不是实际替换它。据我所知,我的replaceChild()的语法是正确的 - 想法?
编辑完整代码:
this.bold = function() {
var selection = this.selection;
var selectedContents = selection.extractContents();
var existingSelector = selectedContents.querySelector("b");
if (existingSelector) {
var html = existingSelector.innerHTML;
var node = document.createTextNode(html);
console.log(node);
existingSelector.parentNode.replaceChild(node, existingSelector);
}
else {
var b = document.createElement("b");
b.appendChild(selectedContents);
selection.deleteContents();
selection.insertNode(b);
}
this.restoreSelection(selection);
}