How can I get, manipulate and replace a text node using jQuery?

后端 未结 3 378
时光取名叫无心
时光取名叫无心 2021-01-19 11:41

Here is my code:

  • Printing from $10
  • 相关标签:
    3条回答
    • 2021-01-19 12:05

      Here's how to select a text node.

      Here's (the skeleton of) what you do once you've got 'em:

      $('li.det_price').contents().filter(function()
      { 
          return this.nodeType == 3;
      }).text(function (i, text)
      {
          return text.replace(/* your schtuff here */);
      });
      

      So apparently jQuery doesn't play that nicely with text nodes

      Time to get (a little) hacky:

      var rnotwhite = /\S/; // to omit text nodes that are solely white space
                            // tweak this as needed
      $('li.det_price').contents().filter(function()
      { 
          return this.nodeType === 3 && rnotwhite.test($(this).text());
      }).text(function (i, text)
      {
          this.replaceWholeText(text + ' replaced');
          // or, for more cross-browser-ness
          // this.nodeValue = text + ' replaced';
      });
      

      --> Check out this sweet demo <--

      --> IE-compatible demo here <--

      Now here's the deal: if you have control of the markup, the best solution for this is to wrap the text nodes you're actually interested in, in <span>s, like this:

      <li class="det_price">
        <a href="/designer/customize/278258?dpid=1">Printing</a><span> from $10</span>
      </li>
      

      and then you can just do this (way less sketch, IMO):

      $('li.det_price > a + span').text(function (i, text)
      {
          return text + ' replaced';
      });
      

      --> More demo goodness <--

      0 讨论(0)
    • 2021-01-19 12:09

      $("li.det_price a").text() would get you the text of that LI (and, unfortunately, of all LI nodes with that class reference). To get just the text of that particular LI you would have to give it an ID, or find some other way to identify it uniquely.

      Once you do identify it uniquely, you could simply put a string in the .text() braces to change what you had. For example,

      $("li.det_price a").text('Not Printing') would change your text above from 'Printing' to 'Not Printing'.

      0 讨论(0)
    • 2021-01-19 12:12

      You need to use the each function:

      $("li.det_price a").each(function(index, Element){
         //Element holds the current anchor, manipulate it's contents at will
         $("Element").val("some new value...");
      })
      
      0 讨论(0)
    提交回复
    热议问题