”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何使用jQuery或纯JavaScript在元素中选择文本节点?

如何使用jQuery或纯JavaScript在元素中选择文本节点?

发布于2025-03-24
浏览:940

How Can I Select Text Nodes within an Element Using jQuery or Pure JavaScript?
使用jquery

选择文本节点

选择具有JQuery的元素的后代文本节点需要一些创造力。 While jQuery does not offer a specific function for this task, it's possible to combine the methods contents() and find() to achieve the desired result.

jQuery Solution

var getTextNodesIn = function(el) { 返回$(el).find(“:not(iframe)”)。 返回this.nodeType == 3; }); }; getTextNodesin(el);

Pure JavaScript Solution
var getTextNodesIn = function(el) {
    return $(el).find(":not(iframe)").addBack().contents().filter(function() {
        return this.nodeType == 3;
    });
};

getTextNodesIn(el);

If you prefer a pure JavaScript approach, the following function can be used:

function getTextNodesIn(node, includeWhitespaceNodes) { var textnodes = [],nonwhitespacematcher = /\ s /; 函数getTextNodes(node){ if(node.nodeType == 3){ if(包括whitespacenodes || nonwhitespacematcher.test(node.nodevalue)){ textnodes.push(node); } } 别的 { for(var i = 0,len = node.childnodes.length; i 此函数递归遍历DOM树,根据其节点类型识别文本节点。它允许通过传递一个参数包含whitespace节点。[&& &&&&华

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3