」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用jQuery或純JavaScript在元素中選擇文本節點?

如何使用jQuery或純JavaScript在元素中選擇文本節點?

發佈於2025-03-24
瀏覽:811

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