代码之家  ›  专栏  ›  技术社区  ›  ika

如何在不更改元素的子元素的情况下更改元素的文本?

  •  98
  • ika  · 技术社区  · 14 年前

    我想动态更新元素的文本:

    <div>
       **text to change**
       <someChild>
           text that should not change
       </someChild>
       <someChild>
           text that should not change
       </someChild>
    </div>
    

    我刚接触jquery,所以这项任务对我来说似乎很有挑战性。 有人能给我指一个要使用的函数/选择器吗?

    如果可能的话,我希望在不为需要更改的文本添加新容器的情况下进行此操作。

    14 回复  |  直到 6 年前
        1
  •  60
  •   Community CDub    8 年前

    Mark’s got a better solution using jQuery

    childNodes

    <div id="your_div">
       **text to change**
       <p>
           text that should not change
       </p>
       <p>
           text that should not change
       </p>
    </div>
    

    var your_div = document.getElementById('your_div');
    
    var text_to_change = your_div.childNodes[0];
    
    text_to_change.nodeValue = 'new text';
    

    <div> var your_div = $('your_div').get(0);

        2
  •  57
  •   Mark Baijens    6 年前

    first()

    jQuery.fn.textNodes = function() {
      return this.contents().filter(function() {
        return (this.nodeType === Node.TEXT_NODE && this.nodeValue.trim() !== "");
      });
    }
    
    $(document).ready(function(){
      $('#replaceAll').on('click', function() {
        $('#testSubject').textNodes().replaceWith('Replaced');
      });
    
      $('#replaceFirst').on('click', function() {
        $('#testSubject').textNodes().first().replaceWith('Replaced First');
      });
    });
    p {
      margin: 0px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="testSubject">
       **text to change**
       <p>text that should not change</p>
       <p>text that should not change</p>
       **also text to change**
       <p>text that should not change</p>
       <p>text that should not change</p>
       **last text to change**
    </div>
    <button id="replaceFirst">Replace First</button>
    <button id="replaceAll">Replace All</button>

    $("div").contents().filter(function(){ return this.nodeType == 3; }).first().replaceWith("change text");
    

    $("div").contents().filter(function(){ return this.nodeType == 3; })
    .filter(':first').text("change text");
    

    http://api.jquery.com/contents/

        3
  •  50
  •   user372551    10 年前

    See In action

    $(function() {
      $('input[type=button]').one('click', function() {
        var cache = $('#parent').children();
        $('#parent').text('Altered Text').append(cache);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="parent">Some text
      <div>Child1</div>
      <div>Child2</div>
      <div>Child3</div>
      <div>Child4</div>
    </div>
    <input type="button" value="alter text" />
        4
  •  9
  •   holmis83    9 年前
    <div id="divtochange">
        **text to change**
        <div>text that should not change</div>
        <div>text that should not change</div>
    </div>
    
    $(document).ready(function() {
        $("#divtochange").contents().filter(function() {
                return this.nodeType == 3;
            })
            .replaceWith("changed text");
    });
    

        5
  •  6
  •   MrBojangles    11 年前

    <div id="header">
       <span class="my-text">**text to change**</span>
       <div>
           text that should not change
       </div>
       <div>
           text that should not change
       </div>
    </div>
    

    $('#header .mytext').text('New text here')
    
        6
  •  4
  •   Tim Down    14 年前

    <div id="foo">
       **text to change**
       <someChild>
           text that should not change
       </someChild>
       <someChild>
           text that should not change
       </someChild>
    </div>
    

    var div = document.getElementById("foo");
    div.firstChild.data = "New text";
    

    <div>

    var child = div.firstChild;
    while (child) {
        if (child.nodeType == 3) {
            child.data = "New text";
            break;
        }
        child = child.nextSibling;
    }
    
        7
  •  2
  •   geg    9 年前

    $.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>
        8
  •  1
  •   Yasser Shaikh    12 年前

    http://jsfiddle.net/qYUBp/7/

    <div id="header">
       **text to change**
       <div>
           text that should not change
       </div>
       <div>
           text that should not change
       </div>
    </div>
    

    var tmp=$("#header>div").html();
    $("#header").text("its thursday").append(tmp);
    
        9
  •  1
  •   Lomanic user1254723    7 年前

    <div id="parent"> Some text
        <div>Child1</div>
        <div>Child2</div>
        and some other text
        <div>Child3</div>
        <div>Child4</div>
        and here we are again
    </div>
    

        $('#parent').contents().filter(function() {
            return this.nodeType == Node.TEXT_NODE && this.nodeValue.trim() != '';
        }).each(function() {
        		//You can ignore the span class info I added for my particular application.
            $(this).replaceWith(this.nodeValue.replace(/(\w+)/g,"<span class='IIIclassIII$1' onclick='_mc(this)' onmouseover='_mr(this);' onmouseout='_mt(this);'>$1X</span>"));
    	});
    <script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
    <div id="parent"> Some text
        <div>Child1</div>
        <div>Child2</div>
        and some other text
        <div>Child3</div>
        <div>Child4</div>
        and here we are again
    </div>

    jsfiddle

        10
  •  0
  •   pitx3    14 年前

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

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

        11
  •  0
  •   macio.Jun    12 年前

    $("div").contents().filter(function(){ 
      return this.nodeType == 3; 
    })[0].nodeValue = "The text you want to replace with"
    
        12
  •  0
  •   br4nnigan    10 年前

    $.fn.textnodes = function () {
        return this.contents().filter(function (i,n) {
            return n.nodeType == 3 && n.textContent.trim() !== "";
        });
    };
    
    $("div").textnodes()[0] = "changed text";
    
        13
  •  0
  •   Howard    8 年前

    $.fn.toText = function(str) {
        var cache = this.children();
        this.text(str).append(cache);
    }
    

    <div id="my-div">
       **text to change**
       <p>
           text that should not change
       </p>
       <p>
           text that should not change
       </p>
    </div>
    

    $("#my-div").toText("helloworld");
    
        14
  •  -2
  •   E_net4 Tunn    6 年前

    document.querySelector('#your-div-id').childNodes[0].nodeValue = 'new text';
    

    document.querySelector('#your-div-id')

    .childNodes[0]

    .nodeValue = 'new text'