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

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

If I have html like this:

  • This is some text First span text
  • 相关标签:
    25条回答
    • 2020-11-21 06:35

      Easier and quicker:

      $("#listItem").contents().get(0).nodeValue
      
      0 讨论(0)
    • 2020-11-21 06:36

      This seems like a case of overusing jquery to me. The following will grab the text ignoring the other nodes:

      document.getElementById("listItem").childNodes[0];
      

      You'll need to trim that but it gets you what you want in one, easy line.

      EDIT

      The above will get the text node. To get the actual text, use this:

      document.getElementById("listItem").childNodes[0].nodeValue;
      
      0 讨论(0)
    • 2020-11-21 06:37

      Try this:

      $('#listItem').not($('#listItem').children()).text()
      
      0 讨论(0)
    • 2020-11-21 06:40
      $($('#listItem').contents()[0]).text()
      

      Short variant of Stuart answer.

      or with get()

      $($('#listItem').contents().get(0)).text()
      
      0 讨论(0)
    • 2020-11-21 06:42

      Use an extra condition to check if innerHTML and innerText are the same. Only in those cases, replace the text.

      $(function() {
      $('body *').each(function () {
          console.log($(this).html());
          console.log($(this).text());
          if($(this).text() === "Search" && $(this).html()===$(this).text())  {
              $(this).html("Find");
          }
      })
      })
      

      http://jsfiddle.net/7RSGh/

      0 讨论(0)
    • 2020-11-21 06:43
      jQuery.fn.ownText = function () {
          return $(this).contents().filter(function () {
              return this.nodeType === Node.TEXT_NODE;
          }).text();
      };
      
      0 讨论(0)
    提交回复
    热议问题