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

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

If I have html like this:

  • This is some text First span text
  • 25条回答
    •  终归单人心
      2020-11-21 06:44

      isn't the code:

      var text  =  $('#listItem').clone().children().remove().end().text();
      

      just becoming jQuery for jQuery's sake? When simple operations involve that many chained commands & that much (unnecessary) processing, perhaps it is time to write a jQuery extension:

      (function ($) {
          function elementText(el, separator) {
              var textContents = [];
              for(var chld = el.firstChild; chld; chld = chld.nextSibling) {
                  if (chld.nodeType == 3) { 
                      textContents.push(chld.nodeValue);
                  }
              }
              return textContents.join(separator);
          }
          $.fn.textNotChild = function(elementSeparator, nodeSeparator) {
          if (arguments.length<2){nodeSeparator="";}
          if (arguments.length<1){elementSeparator="";}
              return $.map(this, function(el){
                  return elementText(el,nodeSeparator);
              }).join(elementSeparator);
          }
      } (jQuery));
      

      to call:

      var text = $('#listItem').textNotChild();
      

      the arguments are in case a different scenario is encountered, such as

    • some textmore textagain more
    • second textmore textagain more
    • var text = $("li").textNotChild(".....","");

      text will have value:

      some textagain more.....second textagain more
      

    提交回复
    热议问题