Question

I want to change the text for "new discussion" for the Discussion Board web part to "new post."

I've written this script that works when I try it in the console from Chrome dev tools (and yes, I do add the script tags when I am adding it to SharePoint)

window.onload = function() {
  anchor_container = document.getElementById("forum1-NewPostLink");
  span_container = anchor_container.childNodes[1];
  span_container.textContent = "new post";
}

But the above script does not work when I embed the code onto the page. The error that it reports is

Uncaught TypeError: Cannot read property 'childNodes' of null at Home.aspx:744

When I try calling anchor_container from the console, it'll report null, which leads me to believe that it's not selecting the element. This doesn't seem like a Javascript issue to me, but rather an issue with how Javascript is interacting with SharePoint.

Question: What can I do to get my script working in SharePoint?

Note: I do not have jQuery added to our SharePoint site at the current time, and would rather not add it, since the latest version of ECMAScript has a lot of the same features.

Was it helpful?

Solution

Most likely you need to add _spBodyOnLoadFunctionNames.push()

then wrap your code in a function, which will be called once SharePoint loads it's contents. Yes you are using window.load, but SharePoint has it's own events that fire when content is done fetching and loading.

Something like:

_spBodyOnLoadFunctionNames.push("changeNewPost");

function changeNewPost(){
  anchor_container = document.getElementById("forum1-NewPostLink");
  span_container = anchor_container.childNodes[1];
  span_container.textContent = "new post";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top