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

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

If I have html like this:

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

      Simple answer:

      $("#listItem").contents().filter(function(){ 
        return this.nodeType == 3; 
      })[0].nodeValue = "The text you want to replace with" 
      
      0 讨论(0)
    • 2020-11-21 06:30

      This is an old question but the top answer is very inefficient. Here's a better solution:

      $.fn.myText = function() {
          var str = '';
      
          this.contents().each(function() {
              if (this.nodeType == 3) {
                  str += this.textContent || this.innerText || '';
              }
          });
      
          return str;
      };
      

      And just do this:

      $("#foo").myText();
      
      0 讨论(0)
    • 2020-11-21 06:32

      You can try this

      alert(document.getElementById('listItem').firstChild.data)
      
      0 讨论(0)
    • 2020-11-21 06:33

      Using plain JavaScript in IE 9+ compatible syntax in just a few lines:

      let children = document.querySelector('#listItem').childNodes;
      
      if (children.length > 0) {
          childrenLoop:
          for (var i = 0; i < children.length; i++) {
              //only target text nodes (nodeType of 3)
              if (children[i].nodeType === 3) {
                  //do not target any whitespace in the HTML
                  if (children[i].nodeValue.trim().length > 0) {
                      children[i].nodeValue = 'Replacement text';
                      //optimized to break out of the loop once primary text node found
                      break childrenLoop;
                  }
              }
          }
      }
      
      0 讨论(0)
    • 2020-11-21 06:34

      Similar to the accepted answer, but without cloning:

      $("#foo").contents().not($("#foo").children()).text();
      

      And here is a jQuery plugin for this purpose:

      $.fn.immediateText = function() {
          return this.contents().not(this.children()).text();
      };
      

      Here is how to use this plugin:

      $("#foo").immediateText(); // get the text without children
      
      0 讨论(0)
    • 2020-11-21 06:35

      I liked this reusable implementation based on the clone() method found here to get only the text inside the parent element.

      Code provided for easy reference:

      $("#foo")
          .clone()    //clone the element
          .children() //select all the children
          .remove()   //remove all the children
          .end()  //again go back to selected element
          .text();
      
      0 讨论(0)
    提交回复
    热议问题