Reputation: 1263
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?
Upvotes: 7
Views: 3166
Reputation: 6726
This will change the value of the first node (which is a text node in your example):
$('#1').contents()[0].nodeValue = 'new text';
Upvotes: 12
Reputation: 32154
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");
Upvotes: 0
Reputation: 956
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.
Upvotes: 0
Reputation: 11042
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>');
P.S. I don't think id
's that begin with a number are valid.
Upvotes: -1
Reputation: 3259
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');
Upvotes: 0
Reputation: 1535
Try the following
<div id="1">
<span id='myspan'>some text</span>
<div id="2"></div>
</div>
Then use;
$('#myspan').text('new text');
Upvotes: 0