How can I change an element's text without changing its child elements?

前端 未结 14 2084
难免孤独
难免孤独 2020-11-22 07:30

I\'d like to update element\'s text dynamically:

**text to change** text t
相关标签:
14条回答
  • 2020-11-22 08:25

    I think you're looking for .prependTo().

    http://api.jquery.com/prependTo/

    We can also select an element on the page and insert it into another:

    $('h2').prependTo($('.container'));

    If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned):

    <div class="container">  
      <h2>Greetings</h2>
      <div class="inner">Hello</div>
      <div class="inner">Goodbye</div> 
    </div>
    

    If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

    0 讨论(0)
  • 2020-11-22 08:27

    $.fn.textPreserveChildren = function(text) {
      return this.each(function() {
        return $(this).contents().filter(function() {
          return this.nodeType == 3;
        }).first().replaceWith(text);
      })
    }
    
    setTimeout(function() {
      $('.target').textPreserveChildren('Modified');
    }, 2000);
    .blue {
      background: #77f;
    }
    .green {
      background: #7f7;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    
    <div class="target blue">Outer text
      <div>Nested element</div>
    </div>
    
    <div class="target green">Another outer text
      <div>Another nested element</div>
    </div>

    0 讨论(0)
提交回复
热议问题