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

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

If I have html like this:

  • This is some text First span text
  • 25条回答
    •  执念已碎
      2020-11-21 06:45

      I presume this would be a fine solution also - if you want to get contents of all text nodes that are direct children of selected element.

      $(selector).contents().filter(function(){ return this.nodeType == 3; }).text();
      

      Note: jQuery documentation uses similar code to explain contents function: https://api.jquery.com/contents/

      P.S. There's also a bit uglier way to do that, but this shows more in depth how things work, and allows for custom separator between text nodes (maybe you want a line break there)

      $(selector).contents().filter(function(){ return this.nodeType == 3; }).map(function() { return this.nodeValue; }).toArray().join("");
      

    提交回复
    热议问题