最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change text in div without affecting child elements - Stack Overflow

programmeradmin3浏览0评论

I need to modify the following HTML using Javascript,

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

I have tried using $('#1').text('new text'); However, this unintentionally removes <div id="2">

How should I change some text, without changing the surrounding elements?

I need to modify the following HTML using Javascript,

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

I have tried using $('#1').text('new text'); However, this unintentionally removes <div id="2">

How should I change some text, without changing the surrounding elements?

Share Improve this question edited Jun 30, 2014 at 15:17 1234567 9566 silver badges22 bronze badges asked Jun 30, 2014 at 15:09 Constantine GladkyConstantine Gladky 1,2636 gold badges27 silver badges46 bronze badges 1
  • 3 String.replace? Put the text in its own element? – putvande Commented Jun 30, 2014 at 15:10
Add a ment  | 

6 Answers 6

Reset to default 12

This will change the value of the first node (which is a text node in your example):

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

JSFiddle

Try the following

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

Then use;

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

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

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

And in your JavaScript:

//JavaScript
$('#some-text').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. Keep in mind that you can use any type of element you want, you don't have to use span specifically. You can change this to div or p and you'll still achieve the same result.

the best solution is to check the node type as Node.TEXT_NODE and nodeValue is not 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/LM63t/

P.S. I don't think id's that begin with a number are valid.

发布评论

评论列表(0)

  1. 暂无评论