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

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

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

**text to change** text t
14条回答
  •  醉梦人生
    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;
    }
    
    
    
    Outer text
    Nested element
    Another outer text
    Another nested element

提交回复
热议问题