Get Root Web From Site Collection Using PnP JavaScript Library

Introduction

PnP-JS-Core library contains a 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,

PnP-JS-Core Library

SharePoint has a lot of building blocks in collections which are used to form a SharePoint site. Those are used to manage the contents, generate reports based on contents and 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 are used to return 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 Assets or Style Library,

    1. Download pnp.js PnP JS file.

    2. Download fetch.js Used by PnP js file to handle web requests and responses (Required in IE)

    3. Download promise.js Used by PnP js file to handle web requests and responses (Required in IE)

  2. Create new web part page and insert Content Editor web part.

  3. Create a sample.html file in Site Assets or Style library and insert the below code snippet.
    1. <!-- Required JS file -->  
    2. <script type="text/javascript" src="/siteassets/scripts/fetch.js"></script>  
    3. <script type="text/javascript" src="/siteassets/scripts/promise.min.js"></script>  
    4. <script type="text/javascript" src="/siteassets/scripts/pnp.min.js"></script>  
    5.   
    6. <div id="sample"></div>  
    7.   
    8. <script type="text/javascript">  
    9. //The below PnP property used to return the root website of the site collection  
    10. $pnp.sp.site.rootWeb.get().then(function(web) {  
    11.   
    12.    document.getElementById("sample").innerText = "Title: " + web.Title + "\r\n" + "Description: " + web.Description;  
    13.   
    14. }).catch(function(err) {  
    15.    alert(err);  
    16. });  
    17. </script>  

  4. Add the URL of sample.html file to the content editor webpart.

  5. Click ok to apply the changes to the webpart and save the page.

  6. Now the page displays the title and description of the root website.

Output

Conclusion

PnP-JS-Core library has a lot of simple extension properties and methods that help increases the performance and reduce the number of lines for code.