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?
-
3
String.replace
? Put the text in its own element? – putvande Commented Jun 30, 2014 at 15:10
6 Answers
Reset to default 12This 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.