简体   繁体   English

如何在不影响子元素的情况下更改div中的文本

[英]How to change text in div without affecting child elements

I need to modify the following HTML using Javascript, 我需要使用Javascript修改以下HTML,

<div id="1">
   some text
   <div id="2"></div>
</div>

I have tried using $('#1').text('new text'); 我尝试过使用$('#1').text('new text'); However, this unintentionally removes <div id="2"> 但是,这无意中删除了<div id="2">

How should I change some text , without changing the surrounding elements? 如何在不改变周围元素的情况下更改some text

This will change the value of the first node (which is a text node in your example): 这将更改第一个节点 (在您的示例中为文本节点)的值:

$('#1').contents()[0].nodeValue = 'new text';

JSFiddle 的jsfiddle

Try the following 请尝试以下方法

<div id="1">
   <span id='myspan'>some text</span>
   <div id="2"></div>
</div>

Then use; 然后使用;

$('#myspan').text('new text'); 

If plausible, do something like the following: 如果看似合理,请执行以下操作:

<div id="1">
   <span id="edit">some text</span>
   <div id="2"></div>
</div>

Then, you can edit your text like so: 然后,您可以像这样编辑文本:

$('#edit').text('new text');

Basically, your putting the text you want to edit in its own element with an ID. 基本上,您将要编辑的文本放在带有ID的元素中。 Keep in mind that you can use any type of element you want, you don't have to use span specifically. 请记住,您可以使用任何类型的元素,您不必专门使用span You can change this to div or p and you'll still achieve the same result. 您可以将其更改为divp ,您仍将获得相同的结果。

By the way it is a bad practice to use ids with numbers as elements. 顺便说一下,使用带有数字的元素作为元素是一种不好的做法。

You can add a span if you don't want to change the style of your element. 如果您不想更改元素的样式,可以添加跨度。 So in your case you will do something like this (I removed the numbers as ids): 所以在你的情况下你会做这样的事情(我把数字删除为ids):

<!-- HTML -->
<div id="text-container">
     <span id="some-text">some text</span>
     <div id="something-else"></div>
</div>

And in your JavaScript: 在你的JavaScript中:

//JavaScript
$('#some-text').text('new text');

the best solution is to check the node type as Node.TEXT_NODE and nodeValue is not null: 最好的解决方案是将节点类型检查为Node.TEXT_NODE并且nodeValue不为null:

$('#1')
.contents()
.filter(function() {
  return this.nodeType === Node.TEXT_NODE && this.nodeValue && this.nodeValue.trim();
})
.replaceWith("new text");

My solution as an alternative to others: 我的解决方案作为他人的替代方案:

var text_to_keep = $('#2').text();

$('#1').text('new text').append('<div id="2">' + text_to_keep + '</div>');

http://jsfiddle.net/LM63t/ http://jsfiddle.net/LM63t/

PS I don't think id 's that begin with a number are valid. PS我不认为以数字开头的id是有效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM