Shantha Kumar T
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,
- Simplified JavaScript Library for SharePoint
- PnP-JS-Core Library
- Basic SharePoint web operations using PnP-JS-Core
- Filtering SharePoint Object Collections using PnP-JS-Core
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,
- 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)
- Create new web part page and insert Content Editor web part
- Create a sample.html file in Site Assets or Style library and insert the below code snippet
[code language=”javascript”]
<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>[/code]
Note: StringId and Id.StringValue of content type object returns the id of the content type.
- Add the URL of sample.html file to the content editor web part
- Click ok to apply the changes to the web part and save the page.
- The page returns the id, name and description of the content types associated to the Site Pages library using PnP JavaScript library.
Output:
