In this article, we will cover how to use the PnP JS Core library to get the content type based on id from the SharePoint Online site. To know more about this JavaScript library, check the below links

 
Below are the syntax’s for retrieving the content type object based on the ID from Web level and list level.
 

SYNTAX:

pnp.sp.web.contentTypes.getById(id: string): ContentType

Gets the Content Type based on ID
@param1 > id - ContentType Id
pnp.sp.web.lists.getByTitle(<ListName>).contentTypes.getById(id: string): ContentType

Gets the List associated Content Type based on ID from the List
ListName - Title of the SharePoint List, where we want to add the view
@param1 > id - ContentType Id

EXAMPLE:

The below steps and code snippets used to get the content type from the SharePoint website using PnP JavaScript library,

The below steps and code snippets used to create a new lookup field in SharePoint list 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
  4. Add the URL of sample.html file to the content editor web part
    
    <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>
      
    <span id="outputInfo"></span>
     
    <script type="text/javascript"> 
      
    $pnp.sp.web.contentTypes.getById("0x0101").get().then(function(res) {
     document.getElementById("outputInfo").innerHTML = "ContentType Name: " + res.Name + " - Scope: "+ res.Scope;
    });
     
    </script>
    
    
  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.

Typescript Example:

Typescript is the super set of JavaScript and this PnP JS library is developed using the typescript specification. For developing the SharePoint Framework web parts and make the client side development easier, we can vote for typescript.
The below is the typescript example for getting the content type based on ID.


import pnp from "sp-pnp-js";

pnp.sp.web.contentTypes.getById("0x0101").get().then(data => {
this.domElement.querySelector("#outputInfo").innerHTML = "Content Type Name: "+ data.Name +
" - Scope: "+ data.Scope;
}).catch(err => {
this.domElement.querySelector("#outputInfo").innerHTML = "Unable to create Indexfind ContentType."
});