Reputation: 305
I am trying to replace text within an element on the fly, however .text()
function is replacing both text and HTML. Any thoughts on how I only edit the actual text?
<div>
<h3 class="titleHeading">My Title <a ng-click="openTooltip('getMoreInfo')"><span class="toolTip"></span></a>
<div>
I want to change the words "My Title" to "My New Title", however whenever I use .text() function, it replaces all of my html and my anchor tag disappears.
Here is my jQuery:
$('h3.titleHeading').text("My New Title")
My output is then - again, the code removes my anchor tag which I need for a tooltip.
<div>
<h3 class="titleHeading">My New Title
<div>
Upvotes: 0
Views: 925
Reputation: 10975
To achieve expected result, just update innerText for h3 by contents() data instead of using text()
$('.titleHeading').contents()[0].data = "My New Title"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<h3 class="titleHeading">My Title <a ng-click="openTooltip('getMoreInfo')"><span class="toolTip"></span></a>
<div>
codepen - https://codepen.io/nagasai/pen/YoXXjd?editors=1010
Upvotes: 1
Reputation: 1032
If you do not have access to the code, loop through only the text nodes and replace their textContent with your new content. This will keep the other existing HTML intact.
Taken from this answer.
$('h3.titleHeading').contents().filter(function() {
return this.nodeType == 3
}).each(function(){
this.textContent = this.textContent.replace('My Title','My New Title');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<h3 class="titleHeading">My Title <a ng-click="openTooltip('getMoreInfo')"><span class="toolTip"></span></a>
<div>
Upvotes: 2
Reputation: 1782
You should do a few things as outlined in the code below
<h3>
elementspan
Example
<div>
<h3 class="titleHeading">
<span class="titleHeadingText"> My Title</span>
<a ng-click="openTooltip('getMoreInfo')">
<span class="toolTip"></span>
</a>
</h3>
jQuery
$('h3.titleHeadingText').text("My New Title")
Upvotes: 1
Reputation: 362
When developing HTML, if you have an element with child HTML elements, it is a bad idea to have it contain plain-text as well. This causes problems like what you see here.
An easy solution is to put your text inside a span
. (Note: Don't forget to close your h3
.)
<div>
<h3 class="titleHeading">
<span id="titleHeadingText">My Title</span>
<a ng-click="openTooltip('getMoreInfo')">
<span class="toolTip"></span>
</a>
</h3>
<div>
You can change the elements of the text easily, now, without affecting the other elements.
$("#titleHeadingText").text("My New Title");
Upvotes: 2