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

时间:2010-11-05 14:28:30

标签: javascript jquery

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

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

我是jQuery的新手,所以这项任务似乎对我来说非常具有挑战性。 有人能指点我使用函数/选择器吗?

如果有可能,我想在没有为我需要更改的文本添加新容器的情况下这样做。

15 个答案:

答案 0 :(得分:60)

Mark’s got a better solution using jQuery,但您也可以在常规JavaScript中执行此操作。

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

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

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

当然,您仍然可以使用jQuery首先选择<div>(即var your_div = $('your_div').get(0);)。

答案 1 :(得分:57)

更新2018年

由于这是一个非常流行的答案,我决定通过将textnode选择器添加到jQuery作为插件来更新和美化它。

在下面的代码片段中,您可以看到我定义了一个新的jQuery函数,它可以获取所有(也是唯一的)textNodes。您也可以使用first()函数链接此函数。 我在文本节点上进行修剪,并在修剪后检查它是否为空,因为空格,制表符,新行等也被识别为文本节点。如果你也需要那些节点,那么简单地从jQuery函数中的if语句中删除它。

我添加了一个示例,说明如何替换第一个文本节点以及如何替换所有文本节点。

这种方法可以更容易地阅读代码,并且更容易多次使用它,并且具有不同的用途。

如果您愿意, 2017更新(adrach)仍然可以正常工作。

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>


2017年更新(adrach):

自发布以来,看起来有些事情发生了变化。这是更新版本

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

答案 2 :(得分:51)

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

答案 3 :(得分:10)

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

这只会更改第一个textnode

答案 4 :(得分:6)

只需将要更改的文本包含在要选择的类的范围内。

不一定能回答我所知道的问题,但可能是更好的编码习惯。让事情干净简单

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

答案 5 :(得分:4)

对于您提到的具体案例:

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

答案 6 :(得分:2)

&#13;
&#13;
         WITH a
     AS (SELECT *
         FROM   structure
         WHERE  parent = 125

         UNION ALL
         SELECT m.*
         FROM   structure m
                JOIN a
                  ON m.parent = a.internidstructure)
SELECT *
FROM   a
WHERE  internidstructure IN (SELECT DISTINCT( internidstructure )
                             FROM   dbo.articles
                                    INNER JOIN dbo.structure_article
                                            ON dbo.articles.internidarticle =
dbo.structure_article.internidarticle
WHERE  ( dbo.articles.internidsupplier IN (SELECT
internidsupplier
                         FROM   site_sup
                         WHERE
internidsite = 1) ))
ORDER  BY parent,
          sortno  
&#13;
$.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);
&#13;
.blue {
  background: #77f;
}
.green {
  background: #7f7;
}
&#13;
&#13;
&#13;

答案 7 :(得分:1)

这是另一种方法: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);

答案 8 :(得分:1)

这里有很多很棒的答案,但它们只处理一个带有子节点的文本节点。在我的情况下,我需要在所有文本节点上操作并忽略html子节点但是保留订购。

所以,如果我们有这样的案例:

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

我们可以使用以下代码仅修改文本并保留订购

&#13;
&#13;
    $('#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>"));
	});
&#13;
<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>
&#13;
&#13;
&#13;

以下是jsfiddle的工作

答案 9 :(得分:0)

我认为你正在寻找.prependTo()。

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

  

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

     

$( 'H2')prependTo($( '容器'));

     

如果以这种方式选择的元素是   插入其他地方,它将被移动   进入目标(未克隆):

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

如果有多个目标   但是,克隆的元素   将为其创建inserted元素   第一个目标之后的每个目标。

答案 10 :(得分:0)

简单回答:

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

答案 11 :(得分:0)

Mark回答的问题是你得到空的文本节点。作为jQuery插件的解决方案:

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

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

答案 12 :(得分:0)

这是一个老问题,但你可以做一个这样简单的功能,让你的生活更轻松:

$.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");

答案 13 :(得分:0)

Javascript 方法。选择父 div,我们可以使用 firstChild.textContent

let myDiv = document.getElementById("parentDiv");
myDiv.firstChild.textContent = "** New Text **"

答案 14 :(得分:-2)

2019年版本-简短

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

说明

document.querySelector('#your-div-id')用于选择父项(您要更改文本的元素)

.childNodes[0]选择文本节点

.nodeValue = 'new text'将文本节点值设置为“新文本”