Squirrl
Squirrl

Reputation: 4966

Why does .text().replace() delete my html?

FIDDLE UPDATED TO CLASSES

<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

Answers (1)

Tony
Tony

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);

Demo

Upvotes: 2

Related Questions