如何更改元素的文本而不更改其子元素?

时间:2022-12-06 13:24:46

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?

我是jQuery新手,所以这个任务对我来说很有挑战性。有人能给我指出一个函数/选择器来使用吗?

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

如果可能的话,我希望不为需要修改的文本添加新的容器。

13 个解决方案

#1


49  

Mark’s got a better solution using jQuery, but you might be able to do this in regular JavaScript too.

Mark使用jQuery有一个更好的解决方案,但是您也可以在普通的JavaScript中使用它。

In Javascript, the childNodes property gives you all the child nodes of an element, including text nodes.

在Javascript中,childNodes属性提供元素的所有子节点,包括文本节点。

So, if you knew the text you wanted to change was always going to be the first thing in the element, then given e.g. this HTML:

所以,如果你知道你想要改变的文本总是在元素中是第一件事,那么给出如下HTML:

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

You could do this:

你可以这样做:

var your_div = document.getElementById('your_div');

var text_to_change = your_div.childNodes[0];

text_to_change.nodeValue = 'new text';

Of course, you can still use jQuery to select the <div> in the first place (i.e. var your_div = $('your_div').get(0);).

当然,您仍然可以使用jQuery首先选择

(即var your_div = $('your_div').get(0););

#2


53  

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

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

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

UPDATE 2017 (adrach): it looks like several things changed since this was posted. Here is an updated version

2017年更新(adrach):自从这篇文章发布以来,看起来发生了一些变化。这是一个更新的版本

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

#3


48  

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

#4


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");
});

This changes only the first textnode

这只更改第一个textnode

#5


6  

Just wrap the text you want to change in a span with a class to select.

只需将想要更改的文本打包到一个类中以选择。

Doesn't necessarily answer your question I know, but, probably a better coding practice. Keep things clean and simple

不一定能回答你的问题,我知道,但可能是更好的编码实践。保持事物整洁和简单

<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>

Voilà!

瞧!

$('#header .mytext').text('New text here')

#6


4  

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;
}

#7


2  

$.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  

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

这里还有另一个方法:http://jsfiddle.net/qYUBp/7/

HTML

HTML

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

JQUERY

JQUERY

var tmp=$("#header>div").html();
$("#header").text("its thursday").append(tmp);

#9


1  

Lots of great answers here but they only handle one text node with children. In my case I needed to operate on all text nodes and ignore html children BUT PRESERVE THE ORDERING.

这里有很多很棒的答案,但它们只处理一个带孩子的文本节点。在我的例子中,我需要对所有文本节点进行操作,忽略html子节点,但保留顺序。

So if we have a case like this:

如果我们有这样一个例子:

<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>

We can use the following code to modify the text only AND PRESERVE THE ORDERING

我们可以使用以下代码只修改文本并保持排序

    $('#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>

Here is the jsfiddle of it working

这是它工作的jsfiddle。

#10


0  

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

我想你在找。prependto ()

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

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

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

我们也可以在页面上选择一个元素并将其插入到另一个元素中:

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

$(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.

但是,如果有多个目标元素,则将在第一个目标之后为每个目标创建插入元素的克隆副本。

#11


0  

Simple answer:

简单的回答是:

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

#12


0  

Problem with Mark's answer is that you get empty textnodes aswell. Solution as jQuery plugin:

Mark的答案有一个问题:你也会得到空的textnodes。解决方案为jQuery插件:

$.fn.textnodes = function () {
    return this.contents().filter(function (i,n) {
        return n.nodeType == 3 && n.textContent.trim() !== "";
    });
};

$("div").textnodes()[0] = "changed text";

#13


0  

This is an old question but you can make a simple function like this to make your life easier:

这是一个老问题,但你可以做一个简单的功能,像这样使你的生活更容易:

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

Example:

例子:

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

Usage:

用法:

$("#my-div").toText("helloworld");

#1


49  

Mark’s got a better solution using jQuery, but you might be able to do this in regular JavaScript too.

Mark使用jQuery有一个更好的解决方案,但是您也可以在普通的JavaScript中使用它。

In Javascript, the childNodes property gives you all the child nodes of an element, including text nodes.

在Javascript中,childNodes属性提供元素的所有子节点,包括文本节点。

So, if you knew the text you wanted to change was always going to be the first thing in the element, then given e.g. this HTML:

所以,如果你知道你想要改变的文本总是在元素中是第一件事,那么给出如下HTML:

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

You could do this:

你可以这样做:

var your_div = document.getElementById('your_div');

var text_to_change = your_div.childNodes[0];

text_to_change.nodeValue = 'new text';

Of course, you can still use jQuery to select the <div> in the first place (i.e. var your_div = $('your_div').get(0);).

当然,您仍然可以使用jQuery首先选择

(即var your_div = $('your_div').get(0););

#2


53  

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

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

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

UPDATE 2017 (adrach): it looks like several things changed since this was posted. Here is an updated version

2017年更新(adrach):自从这篇文章发布以来,看起来发生了一些变化。这是一个更新的版本

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

#3


48  

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

#4


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");
});

This changes only the first textnode

这只更改第一个textnode

#5


6  

Just wrap the text you want to change in a span with a class to select.

只需将想要更改的文本打包到一个类中以选择。

Doesn't necessarily answer your question I know, but, probably a better coding practice. Keep things clean and simple

不一定能回答你的问题,我知道,但可能是更好的编码实践。保持事物整洁和简单

<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>

Voilà!

瞧!

$('#header .mytext').text('New text here')

#6


4  

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;
}

#7


2  

$.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  

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

这里还有另一个方法:http://jsfiddle.net/qYUBp/7/

HTML

HTML

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

JQUERY

JQUERY

var tmp=$("#header>div").html();
$("#header").text("its thursday").append(tmp);

#9


1  

Lots of great answers here but they only handle one text node with children. In my case I needed to operate on all text nodes and ignore html children BUT PRESERVE THE ORDERING.

这里有很多很棒的答案,但它们只处理一个带孩子的文本节点。在我的例子中,我需要对所有文本节点进行操作,忽略html子节点,但保留顺序。

So if we have a case like this:

如果我们有这样一个例子:

<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>

We can use the following code to modify the text only AND PRESERVE THE ORDERING

我们可以使用以下代码只修改文本并保持排序

    $('#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>

Here is the jsfiddle of it working

这是它工作的jsfiddle。

#10


0  

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

我想你在找。prependto ()

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

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

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

我们也可以在页面上选择一个元素并将其插入到另一个元素中:

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

$(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.

但是,如果有多个目标元素,则将在第一个目标之后为每个目标创建插入元素的克隆副本。

#11


0  

Simple answer:

简单的回答是:

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

#12


0  

Problem with Mark's answer is that you get empty textnodes aswell. Solution as jQuery plugin:

Mark的答案有一个问题:你也会得到空的textnodes。解决方案为jQuery插件:

$.fn.textnodes = function () {
    return this.contents().filter(function (i,n) {
        return n.nodeType == 3 && n.textContent.trim() !== "";
    });
};

$("div").textnodes()[0] = "changed text";

#13


0  

This is an old question but you can make a simple function like this to make your life easier:

这是一个老问题,但你可以做一个简单的功能,像这样使你的生活更容易:

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

Example:

例子:

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

Usage:

用法:

$("#my-div").toText("helloworld");