in
I have a document with the following structure:
This is some text.
This is an overkill but anyway:
function replaceNodeText() {
if (this.nodeType === 3) {
this.nodeValue = this.nodeValue.replace(replaceNodeText.find, replaceNodeText.replace);
} else {
$(this).contents().each(replaceNodeText);
}
}
replaceNodeText.find = "some";
replaceNodeText.replace = "my";
$("#notice").contents().each(replaceNodeText);
This function will preserve any html present inside the specified element. For example it will work on this HTML:
<div id="notice" class="box generalbox">
<p>This is<br>some text.</p>
<p>This is so<br>me text.</p>
<p>This is <b>some</b> text.</p>
</div>
And produce the following output:
<div id="notice" class="box generalbox">
<p>This is<br>my text.</p>
<p>This is so<br>me text.</p>
<p>This is <b>my</b> text.</p>
</div>
Demo here
var text = $("#notice p").text()
text = text.replace("some", "My");
$("#notice p").text(text);
Try this
$('#notice').html().replace("some", "my");
Salmans answer works good, but if you have more than 1 word in a paragraph it wouldn't be replaced. So use this instead: (with a regex that matches globally)
function replaceNodeText() {
if (this.nodeType === 3) {
this.nodeValue = this.nodeValue.replace(replaceNodeText.regex, replaceNodeText.replace);
} else {
$(this).contents().each(replaceNodeText);
}
}
replaceNodeText.regex = /some/g;
replaceNodeText.replace = "my";
$("#notice").contents().each(replaceNodeText);
Or use this:
(I just changed .replace(x,y) to .split(x).join(y), this is way faster than replace(), see here)
function replaceNodeText() {
if (this.nodeType === 3) {
this.nodeValue = this.nodeValue.split(replaceNodeText.find).join(replaceNodeText.replace);
} else {
$(this).contents().each(replaceNodeText);
}
}
replaceNodeText.find = "some";
replaceNodeText.replace = "my";
$("#notice").contents().each(replaceNodeText);
Demo on jsfiddle
Go a head and try this solution:
newtext = $("#notice p").text().replace("some", "My");
$("#notice p").text(newtext);
Read http://api.jquery.com/text/#text-functionindex--text
$("#notice p").text(function (_, ctx) {
return ctx.replace("some", "My");
});
or
$("#notice p").text($("#notice p").text().replace("some", "My"));
or
var p_tag = $("#notice p");
p_tag.text(p_tag.text().replace("some", "My"));