Using .text() to retrieve only text not nested in child tags

后端 未结 25 1794
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 05:55

If I have html like this:

  • This is some text First span text
  • 25条回答
    •  星月不相逢
      2020-11-21 06:30

      This is an old question but the top answer is very inefficient. Here's a better solution:

      $.fn.myText = function() {
          var str = '';
      
          this.contents().each(function() {
              if (this.nodeType == 3) {
                  str += this.textContent || this.innerText || '';
              }
          });
      
          return str;
      };
      

      And just do this:

      $("#foo").myText();
      

    提交回复
    热议问题