如何使用JavaScript/jQuery在两个元素节点之间找到所有文本节点? [英] How can I find all text nodes between two element nodes with JavaScript/jQuery?

查看:95
本文介绍了如何使用JavaScript/jQuery在两个元素节点之间找到所有文本节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下HTML片段:

Given the following HTML-Fragment:

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

我需要一种算法来使用Javascript获取#x#y之间的Text类型的所有节点.还是有一个JQuery函数可以做到这一点?

I need an algorithm to fetch all nodes of type Text between #x and #y with Javascript. Or is there a JQuery function that does exactly that?

上面示例中生成的Text节点(忽略空白节点)将是:

The resulting Text nodes (whitespace nodes ignored) for the example above would then be:

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

推荐答案

以下内容在所有使用DOM方法且不使用库的主流浏览器中均适用.它也忽略了问题中提到的空白文本节点.

The following works in all major browsers using DOM methods and no library. It also ignores whitespace text nodes as mentioned in the question.

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

Obligatory 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);

这篇关于如何使用JavaScript/jQuery在两个元素节点之间找到所有文本节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆