Create, Retrieve, Update Or Delete Sub Sites On SharePoint Using JavaScript Object Model


Introduction

In this article, you will learn how to retrieve, create, update or delete the sites under a site collection, using JavaScript Object Model (JSOM) on SharePoint 2013 / SharePoint Online sites like O365. The sites are considered as the sub sites within the site collection.


Before executing any operation, load the required scripts like SP.js, SP.RunTime.js. If the scripts are not initialized, use the snippet, given below:

  1. var scriptbaseURL = _spPageContextInfo.webServerRelativeUrl + "_layouts/15/";    

  2. $.getScript(scriptbaseURL + "SP.Runtime.js",    

  3. function ()     {            

  4. $.getScript(scriptbaseURL + "SP.js", RequiredFunctions);        }    

  5. );   


Create Sub Site

The operation will create a sub site within the site collection. 

  • Access the context of the site and the Web object, using root site URL or the current context.

  • Create WebCreationInformation Object. Set the necessary parameters like title, description, URL, Web template, site permission and the language.

  • Add it to the existing Web collections and update the current site. Execute the request.

The code snippet, given below, helps in creating a site.

  1. var rootSiteUrl = "https://abc.sharepoint.com";  

  2. var ctx = new SP.ClientContext(rootSiteUrl);  

  3. var web = ctx.get_web();  

  4. var webInfo = new SP.WebCreationInformation();  

  5. webInfo.set_title('subsite');  

  6. webInfo.set_description('subsite description');  

  7. webInfo.set_url('subsite');  

  8. webInfo.set_webTemplate('STS#0');  

  9. webInfo.set_useSamePermissionsAsParentSite(true);  

  10. webInfo.set_language(1033);  

  11. web.get_webs().add(webInfo);  

  12. web.update();  ctx.executeQueryAsync(function(){      

  13. console.log("Sub Site Created");  },  

  14. function(sender, args){      

  15. console.log("Failed to create sub site : " + args.get_message());  }  

  16. );