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

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

If I have html like this:

  • This is some text First span text
  • 25条回答
    •  猫巷女王i
      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;
                  }
              }
          }
      }
      

    提交回复
    热议问题