插入节点时如何找到最近的父节点

How to find the nearest parent when inserting Node?

本文关键字:最近 父节点 何找 节点 插入      更新时间:2023-09-26

假设我有以下文本:

你好,<span class='blue_mark'>,我叫Bob </span>

假设我想用.red_mark高亮显示Bob。当我这样做时,最近的父节点将是.blue_mark而不是主父节点。我想计算这个,因为我不想让任何跨度嵌套在一起。

这是我的代码:

var selection = document.getSelection();
  var range = selection.getRangeAt(0);
  var contents = range.extractContents();
  var node = document.createElement('span');
  node.classList.add('blue_mark');
  node.appendChild(contents);
  range.insertNode(node);
  selection.removeAllRanges(); //Clear the selection, showing highlight

在insertNode之前,我想检查span是否嵌套在另一个span中。如果是这样,就不要插入并弹出提示。如果没有,则插入内容/

基本上,你不希望有任何重叠的span。所以:

  1. 选择的开始不能在span
  2. 选择的结束不能在span
  3. 选择不能完全包含span

首先是效用函数:

function isInSpan(node) {
    if (node && node.nodeType === 3) {
        node = node.parentNode;
    }
    while (node && node.nodeType === 1) {
        if (node.nodeName.toUpperCase() === "SPAN") {
            return true;
        }
        node = node.parentNode;
    }
    return false;
}

那么,我相信你可以这样检查:

if (isInSpan(range.startContainer) ||
    isInSpan(range.endContainer) ||
    range.cloneContents().querySelector("span")) {
    // Do the alert
} else {
    // Go ahead and create the span
}

(惊喜地看到querySelector出现在DocumentFragment上)