0

I've made a HTML + CSS menu on a page which I happy with. Ideally I wanted the name of the page to appear in it. This way I can use the web part across the site and it will change the page name itself.

I first tried some code to do this

<script>document.write(document.getElementById("ctl00_PlaceHolderMain_wikiPageNameDisplay").innerHTML);</script>

This didn't work as I wanted as it took the pagename.aspx. So if I renamed it to something more readable, the URL would be full of %20s.

I then made a new page using the page library. This would give me a display name field, but now I can't figure out how to show just the display name. The old code I used doesn't work as it looks like it is for wiki pages.

Ganesh Sanap - MVP
  • 44,918
  • 21
  • 30
  • 61

1 Answers1

1

Try using below code:

document.querySelector("h1#pageTitle span").innerText

You can trim the page title like:

document.querySelector("h1#pageTitle span").innerText.trim()

Or for safer side you can use:

document.querySelector("h1#pageTitle1 span") ? document.querySelector("h1#pageTitle span").innerText.trim() : ""

Update from Comments:

Try using below complete code in Script Editor web part. It is working on my SharePoint site:

<div id="customPageTitle"></div>

<script type="text/javascript"> //_spBodyOnLoadFunctionNames.push("runAfterEverythingLoaded");

ExecuteOrDelayUntilScriptLoaded(runAfterEverythingLoaded, &quot;sp.js&quot;);

function runAfterEverythingLoaded() {
    // your code goes here
    var pageTitle = document.querySelector(&quot;h1#pageTitle span&quot;) ? document.querySelector(&quot;h1#pageTitle span&quot;).innerText.trim() : &quot;&quot;;
    document.querySelector(&quot;div#customPageTitle&quot;).innerText = &quot;Page Title is: &quot; + pageTitle;
}

</script>

Output:

enter image description here

To read more about ExecuteOrDelayUntilScriptLoaded() function, check my answer at: Run Javascript after page loads

Ganesh Sanap - MVP
  • 44,918
  • 21
  • 30
  • 61