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.

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, "sp.js");
    
    function runAfterEverythingLoaded() {
        // your code goes here
        var pageTitle = document.querySelector("h1#pageTitle span") ? document.querySelector("h1#pageTitle span").innerText.trim() : "";
        document.querySelector("div#customPageTitle").innerText = "Page Title is: " + pageTitle;
    }
</script>

Output:

enter image description here

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

8
  • I worry if I have missed something here. I wrap your code in script tags but nothing shows on the page. Jan 8 at 7:19
  • Can you please try running this code first in browser's console (developer tools) and see if it works? Jan 8 at 7:41
  • Thank you. First two codes blocks bring back the page title. I just can't get it to show on the page. Jan 8 at 7:43
  • Can you please share any screenshot of where exactly you want to show the page title? or your existing code? Jan 8 at 7:44
  • 1
    Perfect. Updated code works great and I've managed to get it to work in my custom menu too. Thank you! Jan 8 at 8:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.