Reputation: 4966
<p id="boohoo"><b id="why did all this disappear">Old Text</b></p>
<p id="boohoo"><h4 id="why did this not work">Old Text</h4></p>
var x = $('#boohoo').text().replace('Old', 'New');
function whyNotBold() {
$('#boohoo').text(x);
}
Why is there a difference between <b>
and <h4>
? And how can I have the the former <b id="...
html not disappear when I insert the text? I would think .text().replace(...
would only replace text and not affect the html, but that doesnt seem to be the case here since it's deleting it.
Upvotes: 0
Views: 123
Reputation: 7445
Firt of all you have 2 element with the same id, this is wrong. So your replacement work with the first element only.
The second is text() function strips tags and return only text content of your first node which is: Old Text
. When you use text() func to set the text, jquery thinks you want your node <p id="boohoo">
contains text ONLY and it makes this:
<p id="boohoo">New Text</p>
Becase text() func resonsible for text nodes
EDIT:
In your case, you can do what you want like this:
var x = $('b').text().replace('Old', 'New');
function whyNotBold() {
$('b').text(x);
$('h4').text(x);
}
setTimeout(whyNotBold, 300);
Upvotes: 2