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

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

If I have html like this:

  • This is some text First span text
  • 25条回答
    •  陌清茗
      陌清茗 (楼主)
      2020-11-21 06:53

      Just like the question, I was trying to extract text in order to do some regex substitution of the text but was getting problems where my inner elements (ie: ,

      , , etc.) were getting also removed.

      The following code seems to work well and solved all my problems.

      It uses some of the answers provided here but in particular, will only substitute the text when the element is of nodeType === 3.

      $(el).contents().each(function() { 
        console.log(" > Content: %s [%s]", this, (this.nodeType === 3));
      
        if (this.nodeType === 3) {
          var text = this.textContent;
          console.log(" > Old   : '%s'", text);
      
          regex = new RegExp("\\[\\[" + rule + "\\.val\\]\\]", "g");
          text = text.replace(regex, value);
      
          regex = new RegExp("\\[\\[" + rule + "\\.act\\]\\]", "g");
          text = text.replace(regex, actual);
      
          console.log(" > New   : '%s'", text);
          this.textContent = text;
        }
      });
      

      What the above does is loop through all the elements of the given el (which was simply obtained with $("div.my-class[name='some-name']");. For each inner element, it basically ignores them. For each portion of text (as determined by if (this.nodeType === 3)) it will apply the regex substitution only to those elements.

      The this.textContent = text portion simply replaces the substituted text, which in my case, I was looking for tokens like [[min.val]], [[max.val]], etc.

      This short code excerpt will help anyone trying to do what the question was asking ... and a bit more.

    提交回复
    热议问题