Get root web from Site Collection using PnP Javascript library

PnP-JS-Core library contains the number of extensible methods and properties. By using that we can achieve the various actions in a simple code. To know more about this library component, visit the below links,

Simplified JavaScript Library for SharePoint

PnP-JS-Core Library

SharePoint has lot of building blocks in collections which are used to form a SharePoint site. Those are used in manage the contents, generate reports based on contents & settings, etc…

In this post, we will use the PnP-JS-Core method to get the root web site from the Site collection.

Syntax:

pnp.sp.site.rootweb  – Gets the root web of the site collection

Example:

The below steps and code snippet used to returns the root web object and properties from the current site collection.

  1. Download Required files to use PnP-JS-Core library from the below links and upload that to Site Asstes or Style Library
  • Download pnp.js  PnP JS file
  • Download fetch.js Used by PnP js file to handle web requests and responses (Required in IE)
  • Download promise.js Used by PnP js file to handle web requests and responses (Required in IE)
  1. Create new web part page and insert Content Editor web part
  2. Create a sample.html file in Site Assets or Style library and insert the below code snippet
    <!-- Required JS file -->
    <script type="text/javascript" src="/siteassets/scripts/fetch.js"></script> 
    <script type="text/javascript" src="/siteassets/scripts/promise.min.js"></script> 
    <script type="text/javascript" src="/siteassets/scripts/pnp.min.js"></script>
    
    <div id="sample"></div>
    
    <script type="text/javascript">
    //The below PnP property used to return the root website of the site collection
    $pnp.sp.site.rootWeb.get().then(function(web) {
    
     document.getElementById("sample").innerText = "Title: " + web.Title + "\r\n" + "Description: " + web.Description;
    
    }).catch(function(err) {
     alert(err);
    });
    </script>
    
  3. Add the URL of sample.html file to the content editor webpart
  4. Click ok to apply the changes to the webpart and save the page.
  5. Now the page displays the title and description of the root website.

 

Leave a Reply

Your email address will not be published. Required fields are marked *