yes sure
yes sure

Reputation: 97

JQuery replace all contents in a div except tags

I have to replace some characters in all a div, but when I run the code, the function replaces me also the html tags characters

my code is:

$("#main").children().each(function() {
    $(this).html($(this).html().replace(/s/g, "K"));
})
<div id="main">
<p>Some contents that will be replaced... <span>this will not be in a span tag :(</span></p>
</div>

result:

<div id="main">
<p>Kome contentK that will be replaced... <Kpan>this will not be in a Kpan tag :(</Kpan></p>
</div>

Upvotes: 1

Views: 816

Answers (1)

VoteyDisciple
VoteyDisciple

Reputation: 37803

If your goal is to preserve all the markup within the div but replace text within all those tags, that's difficult. You need to find just the text nodes and no other nodes and do the replacement within each of the text nodes individually.

This question may help: How do I select text nodes with jQuery?

Upvotes: 3

Related Questions