I am sure there are many other ways, you might have achieved similar results, but dynamic div ids in SharePage pages give a hard time to many developers.Like most other people, developers love certainty, but SharePoint pages may generate 2 different div ids even for same page, when accessed by 2 different users, because of different permissions.I recently had a requirement to put a direct link to users’ my site document library in the my site host page. It’s a SharePoint 2016 environment, but they were not yet ready to go for OneDrive interface and decided to stick to old my site profile page.
This is how a default left nav (with some css) appears in old style profile landing page
with Apps pointing to “Site Contents” page of logged in user’s my site. The customer wanted to replace this Apps with “My Documents” pointing directly to user’s Document Library.
I know the default behaviour of OneDrive redirection is to show user’s document library view on landing page, but what can I say, customer wasn’t ready for OneDrive yet. And since this requirement was for the profile landing page only, no master page changes or JS injection stuffs… just simple javascript added to the page in a script editor web part.
But the problem, the Div id of this left nav kept on changing, sometimes it was zz10_RootAspMenu,then changed to zz11_RootAspMenu and even zz12_RootAspMenu. You got the idea that simple getelementbyid wouldn’t have worked.
So, here we go…
//Fix My Site link in Left Nav
var itemFoundAtIndex = -1;
//Ensure the link is changed only when user is viewing his/her prfile
if(window.location.href.indexOf("Person.aspx?accountname=") == -1)
{
//Get the left nav element by class name
menuElement = document.getElementsByClassName("root ms-core-listMenu-root static");
//loop through all the element items
for(i=0;i <=menuElement.length;i++)
{
//loop through all the children
for(j=0;j <= menuElement[i].children.length;j++)
{
oldLink = menuElement[i].children[j];
//Find the one to replace
if(oldLink.innerText.indexOf("Apps") != -1)
{
oldLink = oldLink.innerHTML.replace("/_layouts/15/viewlsts.aspx", "/Documents/Forms/My Documents.aspx");
newLink = oldLink.replace(/Apps/g, "My Documents");
menuElement[i].children[j].innerHTML=newLink;
itemFoundAtIndex = j;
break;
}
}
if(itemFoundAtIndex >= 0)
{
break;
}
}
Even though, I am sure, it’s not the best way to achieve this, this works 🙂
Let me know if you found a better way t play with such dynamic divs.
Cheers,
Anupam