How to Replace Text Inside a Div Element

How do I replace text inside a div element?

I would use Prototype's update method which supports plain text, an HTML snippet or any JavaScript object that defines a toString method.

$("field_name").update("New text");
  • Element.update documentation

How to change text inside a div without changing any other element in the div

With element.innerText() you're essentially overwriting the whole content of your div - including other html elements such as the anchor tag.

There's a child attached to your div that actually holds your text.
You can reference it via document.getElementById("title").firstChild along with it's .data property.

function changeText(text) {  document.getElementById("title").firstChild.data = text;}const button = document.getElementById('button');button.addEventListener('click', () => changeText('the new text I want '));
<div class="title" id='title'>Text I want to change  <a href="https://link.com" target=_blank><img src="icon.svg" id='icon'></a></div>
<button id='button'>click here to change text<button>

Replace only text content inside DIV using JavaScript

You have to use querySelector() method, in order to change text content of hyperlink.

document.querySelector("#pageTitle a").innerHTML = "text changed";
<h1 id="pageTitle" class="ms-core-pageTitle">  <span id="DeltaPlaceHolderPageTitleInTitleArea">   <span><span><a title="some title" href="/link/page.aspx">Change only this text and keep the rest</a></span></span>  </span></h1>

Replace only text inside a div using jquery

Text shouldn't be on its own. Put it into a span element.

Change it to this:

<div id="one">
<div class="first"></div>
<span>"Hi I am text"</span>
<div class="second"></div>
<div class="third"></div>
</div>
$('#one span').text('Hi I am replace');

How do I replace text inside a paragraph inside a div element?

There are 2 ways you can change the text within HTML tag

function updateNote(divID, paragraphInnerHTML) {
var updateNoteP = document.getElementById(divID);
//Update Paragraph inside the DIV here
let $targetEle = updateNoteP.childNodes[1]
// use innerHTML
$targetEle.innerHTML = paragraphInnerHTML
// or textContext
$targetEle.textContent = paragraphInnerHTML
}

Replace the text inside a div

You can use contents() along with replaceWith():

$('.left').contents().first().replaceWith("New Text");

Fiddle Demo

Replace a string with HTML inside a div using jQuery

If you are interested in a pure JavaScript approach, you can use the innerHTML() property to replace your string with html like this: