Graigue Graigue - 2 months ago 5
HTML Question

Trying to replace a piece of text without affecting a URL

Can someone tell me how to preserve the url in this replace? when i run this code it finds and replaces the text but removes the link text and just has the word text. I need to preserve the link and this is just a simple example. The actually code I need to work with a a dynamic link so I can just manually replace it.



$(".text_div").text(function () {
return $(this).text().replace("contains", "hello everyone");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text_div">
This div contains some <a href="http://www.google.com">text</a>.
</div>





this give's me


This div hello everyone text.

Answer

Use .html() instead of .text():

$(".text_div").html(function() {
  return $(this).html().replace("contains", "hello everyone");
})

$(".text_div").html(function() {
  return $(this).html().replace("contains", "hello everyone");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text_div">
  This div contains some <a href="http://www.google.com">text</a>.
</div>

Comments