How can I change an element's text without cha

2018-12-31 15:32发布

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

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

I'm new to jQuery, so this task seems to be quite challenging for me. Could someone point me to a function/selector to use?

If it is possible, I'd like to do it without adding a new container for the text I need to change.

13条回答
永恒的永恒
2楼-- · 2018-12-31 16:11

For the specific case you mentioned:

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

... this is very easy:

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

You don't state how you want to generalize this. If, say, you want to change the text of the first text node within the <div>, you could do something like this:

var child = div.firstChild;
while (child) {
    if (child.nodeType == 3) {
        child.data = "New text";
        break;
    }
    child = child.nextSibling;
}
查看更多
墨雨无痕
3楼-- · 2018-12-31 16:12

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.

查看更多
宁负流年不负卿
4楼-- · 2018-12-31 16:13

Update 2018

Since this is a pretty popular answer I decided to update and beautify it a little by adding the textnode selector to jQuery as a plugin.

In the snippet below you can see that I define a new jQuery function that gets all (and only) the textNodes. You can chain of this function as well with for example the first() function. I do a trim on the text node and check if it's not empty after the trim because spaces, tabs, new lines, etc. are also recognized as text nodes. If you need those nodes too then simple remove that from the if statement in the jQuery function.

I added an example how to replace first text node and how to replace all text nodes.

This approach makes it easier to read the code and easier to use it multiple times and with different purposes.

The Update 2017 (adrach) should still work as well if you prefer that.

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>


Update 2017 (adrach):

It looks like several things changed since this was posted. Here is an updated version

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

Original answer (Not working for current versions)

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

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

查看更多
余生请多指教
5楼-- · 2018-12-31 16:16

See In action

Markup :

$(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" />

查看更多
萌妹纸的霸气范
6楼-- · 2018-12-31 16:17

Simple answer:

$("div").contents().filter(function(){ 
  return this.nodeType == 3; 
})[0].nodeValue = "The text you want to replace with"
查看更多
荒废的爱情
7楼-- · 2018-12-31 16:22

Here is yet another method : http://jsfiddle.net/qYUBp/7/

HTML

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

JQUERY

var tmp=$("#header>div").html();
$("#header").text("its thursday").append(tmp);
查看更多
登录 后发表回答