Delete a Folder in SharePoint 2013 Using JavaScript (JSOM)

You can use the SharePoint client object model to retrieve, update and manage data in SharePoint 2013. SharePoint makes the object model available in several forms.

  • .NET Framework redistributable assemblies
  • JavaScript library
  • REST/OData endpoints
  • Windows Phone assemblies
  • Silverlight redistributable assemblies

This article shows how to perform basic operations using the JavaScript object model. You can add a reference to the object model using HTML <script> tags.

The following sections describe tasks that you can complete programmatically and they include JavaScript code examples that demonstrate the operations.

Procedure

Open your SP Site in SharePoint 2013 Designer. Then select an Assets icon in designer ribbon to add a JavaScript file.

add js file

After adding a JavaScript file the file is available in the SharePoint Site Assets folder as in the following:



Go to the SP site page and add a new page to the SharePoint site.



After adding a page select an Insert button in the Ribbon Menu.



Then add a Content Editor Web part into the page.



Edit the WebPart and add a JavaScript file link to the content link.



Save the web part and save the page in the site. Click the button!



List Created Successfully.

Source Code

 

  1. <div><button onclick=" DeleteFolder ()">Click here to DeleteFolder </button></div>  
  2.      
  3.     <div id="displayDiv"></div>  
  4.    <script type="text/javascript">   
  5.     
  6. function deleteFolder() {  
  7.     var clientContext;  
  8.     var oWebsite;  
  9.     var folderUrl;  
  10.   
  11.     clientContext = new SP.ClientContext.get_current();  
  12.     oWebsite = clientContext.get_web();  
  13.   
  14.     clientContext.load(oWebsite);  
  15.     clientContext.executeQueryAsync(function () {  
  16.         folderUrl = oWebsite.get_serverRelativeUrl() + "/Lists/Shared Documents/Folder1";  
  17.         this.folderToDelete = oWebsite.getFolderByServerRelativeUrl(folderUrl);  
  18.         this.folderToDelete.deleteObject();  
  19.   
  20.         clientContext.executeQueryAsync(  
  21.             Function.createDelegate(this, successHandler),  
  22.             Function.createDelegate(this, errorHandler)  
  23.         );  
  24.     }, errorHandler);  
  25.   
  26.     function successHandler() {  
  27.         displayDiv.innerHTML = "Go to the " +  
  28.             "<a href='../Lists/Shared Documents'>document library</a> " +  
  29.             "to make sure the folder is no longer there.";  
  30.     }  
  31.   
  32.     function errorHandler() {  
  33.         displayDiv.innerHTML = "Request failed: " + arguments[1].get_message();  
  34.     }  
  35. }  
  36.   
  37. </script>  

 

Thanks for reading my article.

Similar Articles