How do I select text nodes with jQuery?

前端 未结 11 1532
独厮守ぢ
独厮守ぢ 2020-11-21 04:30

I would like to get all descendant text nodes of an element, as a jQuery collection. What is the best way to do that?

11条回答
  •  -上瘾入骨i
    2020-11-21 05:03

    For some reason contents() didn't work for me, so if it didn't work for you, here's a solution I made, I created jQuery.fn.descendants with the option to include text nodes or not

    Usage


    Get all descendants including text nodes and element nodes

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

    Get all descendants returning only text nodes

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

    Get all descendants returning only element nodes

    jQuery('body').descendants();
    

    Coffeescript Original:

    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)
    

    Drop In Javascript Version

    var __indexOf=[].indexOf||function(e){for(var t=0,n=this.length;t=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

    Unminified Javascript version: http://pastebin.com/cX3jMfuD

    This is cross browser, a small Array.indexOf polyfill is included in the code.

提交回复
热议问题