ysfibm
ysfibm

Reputation: 436

Replace only text content inside DIV using JavaScript

I want to change only text content inside an h1 tag. Here's my code:

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

I've tried this code :

document.getElementById("DeltaPlaceHolderPageTitleInTitleArea").innerHTML = "text changed";

But it doesn't work, here's the result:

<h1 id="pageTitle" class="ms-core-pageTitle">
  <span id="DeltaPlaceHolderPageTitleInTitleArea">text changed</span>

</h1>

Any help would be appreciated

Upvotes: 1

Views: 5315

Answers (4)

Adeleke
Adeleke

Reputation: 1

You are pointing to the id of the h1 tag and not the anchor ()tag containing the text to be changed. this im not not sure will allow you to insert the text exactly where you want it to be. using the query selector or any other means of selecting the tag wrapping the text you what to change will surely do. if you dont mind, jquery selector will do the job much easier

you can try something like $("#DeltaPlaceHolderPageTitleInTitleArea a").text("")

Upvotes: 0

Dhiraj
Dhiraj

Reputation: 1462

You can try out this.

function changeContent(){

var element = document.getElementById('DeltaPlaceHolderPageTitleInTitleArea');
element.children[0].innerHTML = "whatever";
}
<h1 id="pageTitle" class="ms-core-pageTitle">
  <span id="DeltaPlaceHolderPageTitleInTitleArea">

    <a title="some title" href="/link/page.aspx">Change only this text and keep the rest</a>

	</span>
  
  <button name="change content" onClick="changeContent()">change content</button>

</h1>

Upvotes: 2

Vivick
Vivick

Reputation: 4991

What you are doing is changing "DeltaPlaceHolderPageTitleInTitleArea" 's innerHTML therefore you replace :

<span>
<span>
<a title="some title" href="/link/page.aspx">Change only this text and keep the rest</a>
</span>
</span>

with:

text changed

What you wanted to change is the title's text am I right ? To do so :

really basic JS:

document.getElementById("DeltaPlaceHolderPageTitleInTitleArea").children[0].children[0].children[0].innerHTML = "text changed";

a bit more advanced :

document.querySelector("DeltaPlaceHolderPageTitleInTitleArea > span > span > a").innerHTML = "text changed";

Or using jQuery :

$("DeltaPlaceHolderPageTitleInTitleArea > span > span > a").text("text changed");

Upvotes: 2

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48337

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>

Upvotes: 3

Related Questions