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

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

If I have html like this:

  • This is some text First span text
  • 25条回答
    •  借酒劲吻你
      2020-11-21 06:47

      I propose to use the createTreeWalker to find all texts elements not attached to html elements (this function can be used to extend jQuery):

      function textNodesOnlyUnder(el) {
        var resultSet = [];
        var n = null;
        var treeWalker  = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, function (node) {
          if (node.parentNode.id == el.id && node.textContent.trim().length != 0) {
            return NodeFilter.FILTER_ACCEPT;
          }
          return NodeFilter.FILTER_SKIP;
        }, false);
        while (n = treeWalker.nextNode()) {
          resultSet.push(n);
        }
        return resultSet;
      }
      
      
      
      window.onload = function() {
        var ele = document.getElementById('listItem');
        var textNodesOnly = textNodesOnlyUnder(ele);
        var resultingText = textNodesOnly.map(function(val, index, arr) {
          return 'Text element N. ' + index + ' --> ' + val.textContent.trim();
        }).join('\n');
        document.getElementById('txtArea').value = resultingText;
      }
    • This is some text First span text Second span text
    提交回复
    热议问题