PnP-JS-Core: Get content types associated to SharePoint List

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,

This post explains,

How to get all content types associated to the SharePoint List or Library using PnP JavaScript Core component.

Example:

The below steps and code snippet used to return all content types which are associated to Site Pages library using PnP JavaScript library,

  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)
  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
    <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">
    //contentTypes propety returns the collection content types associated to the SharePoint list / library
    $pnp.sp.web.lists.getByTitle("Site Pages").contentTypes.get().then(function(result) {
        var contentTypes = "<strong>List: SitePages</strong>";
        for (var i = 0; i < result.length; i++) {
            contentTypes += "Title: " + result[i].Name + "<br/>";
            contentTypes += "ID: " + result[i].StringId + "<br/>";
            contentTypes += "Description: " + result[i].Description + "<br/><br/>";
    
        }
        //console.log(contentTypes);
        document.getElementById("sample").innerHTML = contentTypes;
    
    });
     </script>
     
     
     

    Note: StringId and Id.StringValue of content type object returns the id of the content type.

  4. Add the URL of sample.html file to the content editor web part
  5. Click ok to apply the changes to the web part and save the page.
  6. The page returns the id, name and description of the content types associated to the Site Pages library using PnP JavaScript library.

Output:

Get collection of list content types using PnP-JS-Core
Fig 1: Get collection of list content types using PnP-JS-Core

Leave a Reply

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