如何使用jQuery選擇文本節點?

我想獲取一個元素的全部後代文本節點,做爲jQuery集合。 最好的方法是什麼? css


#1樓

也能夠這樣完成: html

var textContents = $(document.getElementById("ElementId").childNodes).filter(function(){
        return this.nodeType == 3;
});

上面的代碼從給定元素的直接子級子節點中過濾textNodes。 node


#2樓

對我來講,普通的老式.contents()彷佛能夠返回文本節點,只須要當心選擇器,以便您知道它們將是文本節點。 jquery

例如,這用pre標籤將TD的全部文本內容包裝在了個人表中,沒有問題。 ajax

jQuery("#resultTable td").content().wrap("<pre/>")

#3樓

jQuery.contents()可與jQuery.filter一塊兒使用以查找全部子文本節點。 稍做改動,您就能夠找到孫子文本節點。 無需遞歸: 正則表達式

$(function() { var $textNodes = $("#test, #test *").contents().filter(function() { return this.nodeType === Node.TEXT_NODE; }); /* * for testing */ $textNodes.each(function() { console.log(this); }); });
div { margin-left: 1em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="test"> child text 1<br> child text 2 <div> grandchild text 1 <div>grand-grandchild text 1</div> grandchild text 2 </div> child text 3<br> child text 4 </div>

jsFiddle api


#4樓

因爲某些緣由, contents()對我不起做用,因此若是它對您不起做用,這是我作的一個解決方案,我建立了jQuery.fn.descendants ,能夠選擇是否包含文本節點 瀏覽器

用法 ide


獲取全部後代,包括文本節點和元素節點 函數

jQuery('body').descendants('all');

獲取全部僅返回文本節點的後代

jQuery('body').descendants(true);

獲取全部僅返回元素節點的後代

jQuery('body').descendants();

Coffeescript原文

jQuery.fn.descendants = ( textNodes ) ->

    # if textNodes is 'all' then textNodes and elementNodes are allowed
    # if textNodes if true then only textNodes will be returned
    # if textNodes is not provided as an argument then only element nodes
    # will be returned

    allowedTypes = if textNodes is 'all' then [1,3] else if textNodes then [3] else [1]

    # nodes we find
    nodes = []


    dig = (node) ->

        # loop through children
        for child in node.childNodes

            # push child to collection if has allowed type
            nodes.push(child) if child.nodeType in allowedTypes

            # dig through child if has children
            dig child if child.childNodes.length


    # loop and dig through nodes in the current
    # jQuery object
    dig node for node in this


    # wrap with jQuery
    return jQuery(nodes)

插入Javascript版本

var __indexOf=[].indexOf||function(e){for(var t=0,n=this.length;t<n;t++){if(t in this&&this[t]===e)return t}return-1}; /* indexOf polyfill ends here*/ jQuery.fn.descendants=function(e){var t,n,r,i,s,o;t=e==="all"?[1,3]:e?[3]:[1];i=[];n=function(e){var r,s,o,u,a,f;u=e.childNodes;f=[];for(s=0,o=u.length;s<o;s++){r=u[s];if(a=r.nodeType,__indexOf.call(t,a)>=0){i.push(r)}if(r.childNodes.length){f.push(n(r))}else{f.push(void 0)}}return f};for(s=0,o=this.length;s<o;s++){r=this[s];n(r)}return jQuery(i)}

未縮小的Javascript版本: http ://pastebin.com/cX3jMfuD

這是跨瀏覽器,代碼中包含一個小的Array.indexOf


#5樓

我獲得了不少帶有可接受的過濾器功能的空白文本節點。 若是僅對選擇包含非空格的文本節點感興趣,請嘗試將條件條件的nodeValue添加到filter函數中,例如簡單的$.trim(this.nodevalue) !== ''

$('element')
    .contents()
    .filter(function(){
        return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
    });

http://jsfiddle.net/ptp6m97v/

或者,爲了不出現內容看起來像空白但不是空白的奇怪狀況(例如,軟連字符&shy;字符,換行符\\n ,製表符等),您能夠嘗試使用正則表達式。 例如, \\S將匹配任何非空白字符:

$('element')
        .contents()
        .filter(function(){
            return this.nodeType === 3 && /\S/.test(this.nodeValue);
        });
相關文章
相關標籤/搜索