Working With Folders In SharePoint 2016 And Office 365 Using JavaScript Object Model

Creating a folder in SharePoint provides an easy way to manage and structure the documents in a library. It also helps to partition the document library and grant the final permission levels, within the library. Moreover, in Explorer view, the folders will work best in organizing and finding the contents. If the folder creation is enabled for a list, we can create the folders for the list as well.

folder

Change the Radio button, shown above, to Yes to enable the folder creation in SharePoint lists. We can create the folders out of the box as well as via the programming model. As a best practice, it is recommended not to create deep levels of nested folder structures as finding the content will become difficult, which defeats the purpose of the folders.

In this article, we will see, how to work with the folders in SharePoint 2016 and Office 365, using JavaScript object model.

Internal Implementation

Scope of the article is:

  • Create a new folder object in Library.
  • Delete an existing folder object.

All these operations will be done, using JavaScript object model.

Create Folder

Let’s see, how we can create a folder instance in SharePoint programmatically from the client side:

  • Add reference to jQuery file:
    1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
    2. <script language="javascript" type="text/javascript">  
  • Within Document ready function call SP.SOD.executeFunc, so as to load the on demand script SP.js. Call the main starting point function say: ‘createFolder’.
    1. SP.SOD.executeFunc('sp.js''SP.ClientContext', createFolder);  
  • Instantiate the client context and get the list instance.
    1. var clientContext = new SP.ClientContext();  
    2. var oWebsite = clientContext.get_web();  
    3. var oList = oWebsite.get_lists().getByTitle('Demo Library');  
  • Create the folder creation object,
    1. //Create Folder using SP.FileSystemObjectType.folder type  
    2. var oListItemCretionInformation= new SP.ListItemCreationInformation();  
    3. oListItemCretionInformation.set_underlyingObjectType(SP.FileSystemObjectType.folder);  
    4. oListItemCretionInformation.set_leafName("NewFolder");  
    5. oListItem= oList.addItem(oListItemCretionInformation);  
    6. oListItem.update();  
  • Load the client context and execute the batch, which will send the request to the Server and perform the entire JavaScript object model operations as a batch.
    1. clientContext.load(oListItem);  
    2. clientContext.executeQueryAsync(Success,Failure);  

Output: Output from the console and UI is shown below:

Output

Output

Full Code

The full code for the creation of a new folder, which uses JavaScript object model is given below:

  1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
  2. <script language="javascript" type="text/javascript">  
  3.     $(document).ready(function() {  
  4.         SP.SOD.executeFunc('sp.js''SP.ClientContext', createFolder);  
  5.     });  
  6.     var oListItem;  
  7.   
  8.     function createFolder() {  
  9.         //Get Client Context , web and list object  
  10.         var clientContext = new SP.ClientContext();  
  11.         var oWebsite = clientContext.get_web();  
  12.         var oList = oWebsite.get_lists().getByTitle('Demo Library');  
  13.         //Create Folder using SP.FileSystemObjectType.folder type  
  14.         var oListItemCretionInformation = new SP.ListItemCreationInformation();  
  15.         oListItemCretionInformation.set_underlyingObjectType(SP.FileSystemObjectType.folder);  
  16.         oListItemCretionInformation.set_leafName("NewFolder");  
  17.         oListItem = oList.addItem(oListItemCretionInformation);  
  18.         oListItem.update();  
  19.         //Load Client Context and execute the batch  
  20.         clientContext.load(oListItem);  
  21.         clientContext.executeQueryAsync(Success, Failure);  
  22.     }  
  23.   
  24.     function Success() {  
  25.         console.log("Newly Created Folder's Title: " + oListItem.get_item('FileLeafRef'));  
  26.     }  
  27.   
  28.     function Failure(sender, args) {  
  29.         console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());  
  30.     }  
  31. </script>  
Delete Folder

Folder deletion can be done in a similar manner.
  • Within Document ready function, call SP.SOD.executeFunc, so as to load the on demand script SP.js. Call the main starting point function say: ‘deleteFolder’.
    1. SP.SOD.executeFunc('sp.js''SP.ClientContext', deleteFolder);  
  • Instantiate the client context and get the list instance.
    1. //Get the client context,Web and Library object  
    2. clientContext = new SP.ClientContext();  
    3. oWeb = clientContext.get_web();  
    4. var oList = oWeb.get_lists().getByTitle('Demo Library');  
  • Format the CAML query to find the folder to be deleted.
    1. var camlQuery = new SP.CamlQuery();  
    2. camlQuery.set_viewXml("<View><Query><Where><And><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>NewFolder</Value></Eq><Eq><FieldRef Name='FSObjType'/><Value Type='Text'>1</Value></Eq></And></Where></Query></View>");  
  • Load the client context and execute the batch
  • In the success call back, iterate through the returned folder collection and delete the folder.
    1. var listItemEnumerator = collListItem.getEnumerator();  
    2. var itemsToDelete = new Array();  
    3. //Get the folder collection  
    4. while (listItemEnumerator.moveNext()) {  
    5.     var oListItem = listItemEnumerator.get_current();  
    6.     itemsToDelete.push(oListItem);  
    7. }  
    8. //Delete the folder  
    9. for (var i = itemsToDelete.length - 1; i >= 0; i--) {  
    10.     itemsToDelete[i].deleteObject();  
    11. }  
    12. var listItemEnumerator = collListItem.getEnumerator();  
    13. var itemsToDelete = new Array();  
    14. //Get the folder collection  
    15. while (listItemEnumerator.moveNext()) {  
    16.     var oListItem = listItemEnumerator.get_current();  
    17.     itemsToDelete.push(oListItem);  
    18. }  
    19. //Delete the folder  
    20. for (var i = itemsToDelete.length - 1; i >= 0; i--) {  
    21.     itemsToDelete[i].deleteObject();  
    22. }  

Output: Output from the console and UI is given below:

Output

Output

Full Code

The full code to remove the folder object is shown below:

  1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
  2. <script language="javascript" type="text/javascript">  
  3.     $(document).ready(function() {  
  4.         SP.SOD.executeFunc('sp.js''SP.ClientContext', deleteFolder);  
  5.     });  
  6.     var oListItem, collListItem, clientContext;  
  7.   
  8.     function deleteFolder() {  
  9.         //Get the client context,Web and Library object  
  10.         clientContext = new SP.ClientContext();  
  11.         oWeb = clientContext.get_web();  
  12.         var oList = oWeb.get_lists().getByTitle('Demo Library');  
  13.         //Format the caml query to get the folder object  
  14.         var camlQuery = new SP.CamlQuery();  
  15.         camlQuery.set_viewXml("<View><Query><Where><And><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>NewFolder</Value></Eq><Eq><FieldRef Name='FSObjType'/><Value Type='Text'>1</Value></Eq></And></Where></Query></View>");  
  16.         collListItem = oList.getItems(camlQuery)  
  17.             //Load the client context and execute the batch  
  18.         clientContext.load(collListItem);  
  19.         clientContext.executeQueryAsync(Success, Failure);  
  20.     }  
  21.   
  22.     function Success() {  
  23.         //get the folder collection enumerator and loop through it  
  24.         var listItemEnumerator = collListItem.getEnumerator();  
  25.         var itemsToDelete = new Array();  
  26.         //Get the folder collection  
  27.         while (listItemEnumerator.moveNext()) {  
  28.             var oListItem = listItemEnumerator.get_current();  
  29.             itemsToDelete.push(oListItem);  
  30.         }  
  31.         //Delete the folder  
  32.         for (var i = itemsToDelete.length - 1; i >= 0; i--) {  
  33.             itemsToDelete[i].deleteObject();  
  34.         }  
  35.         //Execute the batch  
  36.         clientContext.executeQueryAsync(CallSuccess, CallFailure);  
  37.     }  
  38.   
  39.     function Failure(sender, args) {  
  40.         console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());  
  41.     }  
  42.   
  43.     function CallSuccess() {  
  44.         console.log("Folder has been Deleted !");  
  45.     }  
  46.   
  47.     function CallFailure(sender, args) {  
  48.         console.log("Folder Deletion failed with error - " + args.get_message());  
  49.     }  
  50. </script>  
Summary

Thus, we have seen, how to work with the folders, create and delete the folder object in SharePoint, using JavaScript object model. This has been tried and tested in both SharePoint 2016 and Office 365.