How do I select text nodes with jQuery?

前端 未结 11 1531
独厮守ぢ
独厮守ぢ 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: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; }
    
    
    
    child text 1
    child text 2
    grandchild text 1
    grand-grandchild text 1
    grandchild text 2
    child text 3
    child text 4

    jsFiddle

提交回复
热议问题