简体   繁体   中英

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

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>

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");

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>

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("")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM