How do I select text nodes with jQuery?

前端 未结 11 1557
独厮守ぢ
独厮守ぢ 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条回答
  • 2020-11-21 05:10

    If you can make the assumption that all children are either Element Nodes or Text Nodes, then this is one solution.

    To get all child text nodes as a jquery collection:

    $('selector').clone().children().remove().end().contents();
    

    To get a copy of the original element with non-text children removed:

    $('selector').clone().children().remove().end();
    
    0 讨论(0)
  • 2020-11-21 05:13

    Can also be done like this:

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

    The above code filters the textNodes from direct children child nodes of a given element.

    0 讨论(0)
  • 2020-11-21 05:13

    For me, plain old .contents() appeared to work to return the text nodes, just have to be careful with your selectors so that you know they will be text nodes.

    For example, this wrapped all the text content of the TDs in my table with pre tags and had no problems.

    jQuery("#resultTable td").content().wrap("<pre/>")
    
    0 讨论(0)
  • 2020-11-21 05:21

    I had the same problem and solved it with:

    Code:

    $.fn.nextNode = function(){
      var contents = $(this).parent().contents();
      return contents.get(contents.index(this)+1);
    }
    

    Usage:

    $('#my_id').nextNode();
    

    Is like next() but also returns the text nodes.

    0 讨论(0)
  • 2020-11-21 05:26

    jQuery.contents() can be used with jQuery.filter to find all child text nodes. With a little twist, you can find grandchildren text nodes as well. No recursion required:

    $(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

    0 讨论(0)
提交回复
热议问题