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

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

If I have html like this:

  • This is some text First span text
  • 25条回答
    •  灰色年华
      2020-11-21 06:51

      I came up with a specific solution that should be much more efficient than the cloning and modifying of the clone. This solution only works with the following two reservations, but should be more efficient than the currently accepted solution:

      1. You are getting only the text
      2. The text you want to extract is before the child elements

      With that said, here is the code:

      // 'element' is a jQuery element
      function getText(element) {
        var text = element.text();
        var childLength = element.children().text().length;
        return text.slice(0, text.length - childLength);
      }
      

    提交回复
    热议问题