简体   繁体   English

如何使用JavaScript / jQuery找到两个元素节点之间的所有文本节点?

[英]How can I find all text nodes between two element nodes with JavaScript/jQuery?

Given the following HTML-Fragment: 给出以下HTML片段:

<div>
  <p>
    abc <span id="x">[</span> def <br /> ghi
  </p>
  <p>
    <strong> jkl <span id="y">]</span> mno </strong>
  </p>
</div>

I need an algorithm to fetch all nodes of type Text between #x and #y with Javascript. 我需要一个算法来使用Javascript在#x#y之间获取Text类型的所有节点。 Or is there a JQuery function that does exactly that? 或者是否有一个JQuery函数正是这样做的?

The resulting Text nodes (whitespace nodes ignored) for the example above would then be: 以上示例生成的Text节点(忽略空白节点)将是:

['def', 'ghi', 'jkl']

The following works in all major browsers using DOM methods and no library. 以下适用于使用DOM方法且没有库的所有主流浏览器。 It also ignores whitespace text nodes as mentioned in the question. 它还忽略了问题中提到的空白文本节点。

Obligatory jsfiddle: http://jsfiddle.net/timdown/a2Fm6/ 强制性的jsfiddle: http//jsfiddle.net/timdown/a2Fm6/

function getTextNodesBetween(rootNode, startNode, endNode) {
    var pastStartNode = false, reachedEndNode = false, textNodes = [];

    function getTextNodes(node) {
        if (node == startNode) {
            pastStartNode = true;
        } else if (node == endNode) {
            reachedEndNode = true;
        } else if (node.nodeType == 3) {
            if (pastStartNode && !reachedEndNode && !/^\s*$/.test(node.nodeValue)) {
                textNodes.push(node);
            }
        } else {
            for (var i = 0, len = node.childNodes.length; !reachedEndNode && i < len; ++i) {
                getTextNodes(node.childNodes[i]);
            }
        }
    }

    getTextNodes(rootNode);
    return textNodes;
}

var x = document.getElementById("x"),
    y = document.getElementById("y");

var textNodes = getTextNodesBetween(document.body, x, y);
console.log(textNodes);

The following example uses jQuery to find any two elements that are next to each other and may or may not have text nodes between them. 以下示例使用jQuery查找彼此相邻的任何两个元素,它们之间可能有也可能没有文本节点。 This foreach loop will check the resulted elements to find any text nodes and add them to the list. 此foreach循环将检查结果元素以查找任何文本节点并将其添加到列表中。

function getTextNodes() {
    var list = [];
    $(document.body).find("*+*").toArray().forEach(function (el) {
        var prev = el.previousSibling;
        while (prev != null && prev.nodeType == 3) {
            list.push(prev);
            prev = prev.previousSibling;
        }
    });
    return list;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM