如何在jquery中获取文本节点的html?

时间:2011-03-01 22:24:32

标签: jquery textnode

我在我的语言翻译jquery脚本中使用它作为许多部分之一。

当我遍历网页上的所有节点时,这部分抓住节点的文本。

然而,它也抓住了很多隐藏的javascript作为文本节点。

那么有没有办法修改它,只是得到html方面?加上修剪不需要的空格?

这是原始代码。

var content = function (node, txt) {
if (txt) {
    if (node.textContent) {
        node.textContent = txt;
    } else if (node.nodeValue) {
        node.nodeValue = txt;
    }
} else {
    return node.textContent ? node.textContent : node.nodeValue;
}

};

这将有助于显示此代码的上下文。

// recursive tree walker
(function (parent) {
    var childs = parent.childNodes;
    // if childs object has data
    if (childs && childs.length) {
        var i = childs.length; while (i--) {
            // assign node variable to childs object
            node = childs[i];
            // text node found, do the replacement
            if (node.nodeType == 3) {
                // assign the current value to a variable
                var value = content(node);

            } else {
                arguments.callee(node);
            }
        }
    }
})(document.body);

所有这些都是我的语言翻译代码的逻辑,我只想调整输入,以便抓取文本,但不包含页面源代码中的javascript代码。

1 个答案:

答案 0 :(得分:0)

不太确定您发布的功能从何处被调用(如何使用它)。结帐this question但是,它会像您想要的那样。关键是:

nodeType == 3

这就是你检查DOM节点是否是文本节点的方法。除此之外,您可能必须专门处理脚本标记,但您可以:

:not(script)
在你的jquery选择器中

去除它们

相关问题