Replace word in <p> in <div> using jquery
You need to target the p
tag inside the #notice
:
$("#notice p").text(function(i, text) {
return text.replace("some", "My");
});
Update 2020-03
This same logic can now be made even simpler by using an arrow function:
$('#notice p').text((i, t) => t.replace('some', 'My'));
This will work in any browser except Internet Explorer.
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"));
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