Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top