How to create a site or subsite in SharePoint Online?

This article will show you how to create a site in SharePoint Online. In the same way, we will see, how to create a subsite in SharePoint Online/2013/2016/2019. Also, we will check the below things:

  • How to create a site in SharePoint Online or SharePoint 2013/2016/2019
  • How to create a subsite in SharePoint 2013 Online programmatically using CSOM
  • SharePoint Check if subsite exists using CSOM
  • How to Create subsite in SharePoint Online programmatically
  • Create subsite in SharePoint programmatically using server object model
  • Create subsite in SharePoint programmatically using csom (client side object model)
  • How to delete sites and subsites programmatically using CSOM in SharePoint Online
  • How to Get all subsites from a site collection in SharePoint Online using CSOM
  • Get all subsites from a site collection in SharePoint using CSOM
  • Get Subsites of a SharePoint Online Site Collection using PowerShell

Before I explain subsites, I would like to share a few ideas about the hierarchy of SharePoint (On-premises). Please look into the below screenshot.

But in SharePoint Online, We are not creating any farm or web application, directly we are creating site collections.

create site in sharepoint
create site in sharepoint

You can create multiple numbers of subsites under a Site collection in SharePoint. The web application is the parent of the Farm in SharePoint.

Site Collection is the child of the Web Application in SharePoint and the subweb is like a grandchild of the site collection in SharePoint.

There is no difference between a Site collection and subsites; only the hierarchy is different. You can create multiple numbers of subsites under a site collection in SharePoint.

You can inherit the permission from the parent site collection to child subsites. Below, I have listed a few mandatory fields to create a site collection in SharePoint.

  1. Title
  2. Description
  3. URL
  4. TemplateType
  5. Permission

A company has multiple branches in different countries and states. So, we have to create an application in SharePoint which will manage all different sites for a different country.

Suppose My company name is: RajInfotech and it’s located in the USA, CANADA, INDIA, DUBAI. So here, I have to create a Web Application for RajInoftech and Rajinfotech is the parent and we have to create all branches under Rajinfotech main website.

Web Application Name (Company Name)

URL : http:// Rajinfotech.com (Web Application Name)

Site collection (Country Name)

URL : http:// Rajinfotech.com/Sites/INDIA

SubSites (States)

In a country, If we have multiple branch then we have to create a Sub site under a site collection like

URL : http:// Rajinfotech.com/Sites/INDIA/Bangalore

[Video Tutorial] Create a Subsite in SharePoint Online

Below, I have listed a few mandatory fields to create a site collection in SharePoint.

  1. Title
  2. Description
  3. URL
  4. TemplateType
  5. Permission

You can open this video for your better understanding.

Subscribe to EnjoySharePoint YouTube Channel for more SharePoint video tutorials.

This SharePoint video tutorial explains, how to create a subsite in SharePoint Online Office 365.

Create site in SharePoint Online or SharePoint 2013/2016/2019

Step 1: On your SharePoint site navigate to the Settings gear icon and click ‘Add an app’

create site in sharepoint 2013
create site in sharepoint

Step 2 : Next, click on Subsites .

create site in sharepoint 2016
create site in sharepoint 2013

Step 3: Click on New SubSite button in top of the page.

create site in sharepoint 2019
create site in sharepoint 2013

Step 4: Enter your Site Title and description and select Team site as default template and Use same permissions as parent site and click on Create button.

How to create site in SharePoint 2013
create site in sharepoint

Step 5: Once you click on Create, It will take a moment to create a new team site for you. Below screenshot is the new subsite which is created recently.

How to create site in SharePoint 2013
How to create site in SharePoint 2013

This is all about creating a site or subsite in SharePoint. I will explain more about site features in my next article.

Create subsite in SharePoint 2013 Online programmatically using CSOM

Now, I will explain how to create a subsite in SharePoint 2013 Online programmatically using CSOM under a current web site. Here we will use the WebCreationInformation class to create a new website.

Before we start, we need to create a console application in Visual Studio. Here I am using Visual Studio 2010 but you can do the same thing in a higher version of Visual Studio.

Create subsite in SharePoint 2013 Online programmatically using CSOM

Now, we will see how we can create a subsite under a site collection programmatically using CSOM in SharePoint Online.

Step 1: Open your Visual Studio

Step 2: Create a new console application and enter your solution Name and save it in your any drive location.

Create subsite in SharePoint 2013 Online programmatically using CSOM
Create subsite in SharePoint 2013 Online programmatically using CSOM

Step 3: Before we start , we need to add the SharePoint client object model dll in our application. For adding the dll we can add the dll manually under references or we can download it from NuGet gallery.

Step 4: For download the dll from NuGet , we have to go the manage NuGet packages under Tool in Visual Studio.

sharepoint create subsite programmatically
sharepoint create subsite programmatically

Step 5: Download the references which is required to connect SharePoint online. Below is the screenshot of reference file which is required to download.

sharepoint online create subsite programmatically
sharepoint online create subsite programmatically

Step 6: Next click on Install button. Once it will done, we will get an screen to select the project.

create subsite sharepoint 2013 c#
create subsite sharepoint 2013 c#

Step 7: Once you click on OK button , again you will get an screen to click Accept or Decline. Please click on Accept button to go forward.

create subsite sharepoint 2013 c#
create subsite sharepoint 2013 c#

Step 8: Once you click on Accept button, Download will start and you will get your all references inside reference file in your application.

sharepoint create subsite programmatically
sharepoint create subsite programmatically

Step 9: Next open your Program.cs file and write the below code under Main function.

using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace createListusingCSOM
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "[email protected]";
            Console.WriteLine("Enter Your Password Please  ------- ");
            SecureString password = GetPasswordOfYourSite();
            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

            using (var clientContext = new
            ClientContext("https://pikasha12.sharepoint.com/sites/DLH")) 
                {
                // SharePoint Online Credentials  
                clientContext.Credentials = new SharePointOnlineCredentials(userName, password);
                // Get the SharePoint web  
                WebCreationInformation creation = new WebCreationInformation();
                creation.Url = "MyConsoleWeb";
                creation.Title = "WelcomeToConsoleWeb";
                Web newWeb = clientContext.Web.Webs.Add(creation);

                // Retrieve the new web information. 
                clientContext.Load(newWeb, w => w.Title);
                clientContext.ExecuteQuery();
                clientContext.ExecuteQuery();
            }

        }

        private static SecureString GetPasswordOfYourSite()
        {
            ConsoleKeyInfo info;
            //Get the user's password as a SecureString  
            SecureString securePassword = new SecureString();
            do
            {
                info = Console.ReadKey(true);
                if (info.Key != ConsoleKey.Enter)
                {
                    securePassword.AppendChar(info.KeyChar);
                }
            }
            while (info.Key != ConsoleKey.Enter);
            return securePassword;
        }
    }
}

Step 10 : Test the application:

Hit F5 to run the application. Enter the password and then click on Enter button.

create subsite in sharepoint 2013 programmatically csom
create subsite in sharepoint 2013 programmatically csom

This is how to create a subsite in SharePoint 2013/2016/Online programmatically using CSOM (Client object model).

SharePoint Check if subsite exists using CSOM

This SharePoint tutorial explains, how to check if subsite exists using csom. We will use .Net managed client object model (csom) in SharePoint Online to check if subsite exists sharepoint c#.

Here we will create a console application to do the demo on the check is subsite exists sharepoint csom.

Check is subsite exists SharePoint csom

Now, we will write our csom code to check if the subsite exists in SharePoint Online using c#.

Open visual studio and then click on File -> New -> Project…

And then choose Choose Visual C# -> Windows and then choose Console Application from the list of templates.

Now we can add Microsoft.SharePoint.Client.dll from NuGet Package.

Then go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution…

And then search for Microsoft.sharepoint.client and then select Microsoft.SharePoint.Client.Online.CSOM and then click on Install button like below:

check if subsite exists sharepoint c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using System.Security;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
bool isExists;
var password = new SecureString();
foreach (char c in "*********".ToCharArray()) password.AppendChar(c);
var credentials = new SharePointOnlineCredentials("******@OnlySharePoint2013.onmicrosoft.com", password);

using (ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
context.Credentials = credentials;
var web = context.Web;
context.Load(web, w => w.Webs);
context.ExecuteQuery();
var subWeb = (from w in web.Webs where w.Url == "https://onlysharepoint2013.sharepoint.com/sites/Bhawana/MySubSite" select w).SingleOrDefault();
if (subWeb != null)
{
isExists = true;
}
else
{
isExists = false;
}
}
}
}
}

The above code will return true if the SharePoint subsite exists else it will return false.

This is how to check if subsite exists in SharePoint using CSOM.

Create subsite in SharePoint Online programmatically

This SharePoint tutorial explains, how to create a SharePoint subsite programmatically using the server object model and client object model in SharePoint 2013/2016.

Also, we will see how to delete a SharePoint subsite programmatically using the SharePoint client object model (CSOM).

I have used a windows application to create subsites in SharePoint 2016. But the same code will work for SharePoint 2013.

Create subsite in SharePoint programmatically using server object model

Below is the code to create a subsite using SharePoint 2016 server object model.

using (SPSite site = new SPSite("http://mypc:29024/sites/SPTraining/"))
{
using (SPWeb newWeb = site.OpenWeb())
{
newWeb.AllowUnsafeUpdates = true;
SPWebCollection subsites = newWeb.Webs;
SPWeb newSubWeb = subsites.Add("MySiteFromServerObjectModel", "My Site from Server Object Model", "This is a site from server object model.", 1033, "STS#0", true, false);
newWeb.Update();
}
}

Create subsite in SharePoint programmatically using csom (client side object model)

Below is the csom code to create a subsite programmatically using csom in SharePoint 2013/2016.

using (ClientContext ctx = new ClientContext("http://mypc:29024/sites/SPTraining/"))
{
WebCreationInformation websitecreationinfo = new WebCreationInformation();
websitecreationinfo.Url = "MySiteFromClientObjectModel";
websitecreationinfo.Title = "My Site from Client Object Model";
websitecreationinfo.Description = "This is a site from client object model.";
websitecreationinfo.UseSamePermissionsAsParentSite = true;
websitecreationinfo.WebTemplate = "STS#0";
websitecreationinfo.Language = 1033;
Web w = ctx.Site.RootWeb.Webs.Add(websitecreationinfo);
ctx.ExecuteQuery();
}
Create subsite in SharePoint programmatically

Delete sites and subsites programmatically using CSOM in SharePoint Online

Let us see how to delete all sites, subsites programmatically using csom in SharePoint Online.

Here I am testing it using a windows application, you can also do it using a console application to connect to SharePoint Online sites.

To work with SharePoint objects using csom, we need to add the below dlls.

  • Microsoft.SharePoint.Client
  • Microsoft.SharePoint.Client.Runtime

Delete sites and subsites programmatically using CSOM in SharePoint

Below is the full code to delete sites and subsites programmatically from a SharePoint site collection using csom in SharePoint Online.

private void button3_Click(object sender, EventArgs e)
{
using (ClientContext context = new ClientContext(“https://<tenantname>.sharepoint.com/sites/Bhawana/”))
{
string username = ” **********@<tenantname>.onmicrosoft.com”;
context.AuthenticationMode = ClientAuthenticationMode.Default;
var secureString = new SecureString();
foreach (char c in ” **********”)
{
secureString.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials(username, secureString);
try
{
DeleteSites(context, username, secureString);
}
catch (Exception ex)
{
throw;
}
}
}

public void DeleteSites(ClientContext context, string username, SecureString password)
{
Hashtable hsSites = getAllSites(context, context.Url.ToString(), username, password);
foreach (DictionaryEntry item in hsSites)
{
Hashtable hsSubsites = getSubWebs((Web)item.Key, item.Value.ToString(), username, password);
foreach (DictionaryEntry item1 in hsSubsites)
{
ClientContext ct = new ClientContext(item1.Value.ToString());
ct.AuthenticationMode = ClientAuthenticationMode.Default;
ct.Credentials = new SharePointOnlineCredentials(username, password);
Web web1 = ct.Web;
web1.DeleteObject();
ct.ExecuteQuery();
}
ClientContext ctSite = new ClientContext(item.Value.ToString());
ctSite.AuthenticationMode = ClientAuthenticationMode.Default;
ctSite.Credentials = new SharePointOnlineCredentials(username, password);
Web web = ctSite.Web;
web.DeleteObject();
ctSite.ExecuteQuery();
}
}
public Hashtable getAllSites(ClientContext clientContext, string url, string username, SecureString password)
{
Hashtable hsSites = new Hashtable();
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(username, password);
var Web = clientContext.Web;
clientContext.Load(Web, w => w.Webs);
clientContext.ExecuteQuery();
foreach (Web orWebsite in Web.Webs)
{
hsSites.Add(orWebsite, orWebsite.Url);
}
return hsSites;
}

public Hashtable getSubWebs(Web Website, string siteUrl, string username, SecureString password)
{
Hashtable hsSubSites = new Hashtable();
try
{
ClientContext clientContext = new ClientContext(siteUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(username, password);
Web oWebsite = clientContext.Web;
clientContext.Load(oWebsite, website => website.Webs, website => website.Title);
clientContext.ExecuteQuery();
foreach (Web orWebsite in oWebsite.Webs)
{
hsSubSites.Add(orWebsite, orWebsite.Url);
getSubWebs(orWebsite, orWebsite.Url, username, password);
}
}
catch (Exception ex)
{
}
return hsSubSites;
}

By using the above code, we can delete all SharePoint sites and subsite programmatically.

Here, we saw, how to create a subsite programmatically in SharePoint using server object model or client object model (CSOM). Also, we learned how to delete a subsite or site in SharePoint programmatically.

Get all subsites from a site collection in SharePoint Online using CSOM

Now, let us check, how to get all subsites from a site collection in SharePoint Online using .net managed object model (csom). Also, we will see how to get all subsites under a site collection using PowerShell in SharePoint Online Office 365.

We will see how to retrieve all sites excluding the apps or add-in websites from a SharePoint Online site using.Net managed code in SharePoint Online.

Here I will create a console application to run the csom code and we will connect to the SharePoint Online sites.

Get all subsites from a site collection in SharePoint using CSOM

Whenever you will try to retrieve all the subsites of a site collection in SharePoint programmatically using .Net managed object model (csom) code, it will return all the subsites as well as it will return all the apps or add-in websites if you have deployed any SharePoint hosted add-in.

In this SharePoint site collections, I have deployed some SharePoint hosted add-ins.

If you will run the below code it will give you all the sites including the Add-in webs of the site collection from SharePoint Online.

public static void GetAllSubSites()
{
Hashtable mySites = new Hashtable();
ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana");
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
var web = context.Web;
context.Load(web, w => w.Webs);
context.Load(web, w => w.WebTemplate);
context.ExecuteQuery();
foreach (Web orWebsite in web.Webs)
{
if (orWebsite.WebTemplate != "APP")
{
context.Load(orWebsite, w => w.Title, w => w.Url);
context.ExecuteQuery();
mySites.Add(orWebsite.Url, orWebsite.Title);
}
}
}

private static SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<[email protected]>";
            }
            catch
            {
                throw;
            }
        }

All the sites you can see like below:

get all subsites in sharepoint online csom

But sometimes we might not need all our Add-in webs. So we can filter based on the Site template while retrieving all the subsites programmatically in SharePoint.

public static void GetAllSubSites()
{
Hashtable mySites = new Hashtable();
ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana");
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
var web = context.Web;
context.Load(web, w => w.Webs);
context.ExecuteQuery();
foreach (Web orWebsite in web.Webs)
{
context.Load(orWebsite, w => w.Title, w => w.Url);
context.ExecuteQuery();
mySites.Add(orWebsite.Url, orWebsite.Title);
}
}

private static SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<[email protected]>";
            }
            catch
            {
                throw;
            }
        }

Now if you will check I have only 3 sites which it is returning and is required.

Get all subsites from a site collection in SharePoint Online using CSOM

Get Subsites of a SharePoint Online Site Collection using PowerShell

Now, let us see, how to get or retrieve all the subsites from a site collection in SharePoint Online Office 365 using PowerShell.

A user wants to see the list of all the subsites in a given Site Collection in SharePoint Online. It is unfortunate that my site collection was pretty old and was filled with many subsites with multiple levels. So it is closely impossible to harvest the information manually without any slippage.

Below is the PowerShell Script to retrieve subsites from a SharePoint Online site collection.

<# This Script is to get all the subsites in a given site collection from SPO #>

function GetSubSiteDetails {
try {
#Reading artifacts/prerequisites
$strSiteCollURL = Read-Host "Enter the Site Collection URL of SPO (eg. https://onlysharepoint2013.sharepoint.com/sites/krishna)"
$strUserId = Read-Host "Enter the username of SPO (eg. [email protected])"
$strPassword = Read-Host "Please enter the password for $($strUserId)" -AsSecureString

$startedTime = Get-Date
Write-Host "Time Started = " $startedTime
Write-Host "`nAll the Sub Sites in Site Collection $($strSiteCollURL) are::"

#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.Client\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.Client.Runtime\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.Runtime.dll"

#Bind to site collection
$ObjContext = New-Object Microsoft.SharePoint.Client.ClientContext($strSiteCollURL)
$ObjCreds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($strUserId,$strPassword)
$ObjContext.Credentials = $ObjCreds
#Iterating through the Site Collections
Get-SPOWebs($strSiteCollURL)

$completedTime = Get-Date
Write-Host "`nTime Completed = " $completedTime
Write-Host "Script Excecuted Successfully !!!"
}
catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor red
}
}
function Get-SPOWebs($url) {
#Creating object to Site Collection
$objClientCntx = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$objClientCntx.Credentials = $ObjCreds
$objWeb = $objClientCntx.Web
$objClientCntx.Load($objWeb)
$objClientCntx.Load($objWeb.Webs)
try {
$objClientCntx.ExecuteQuery()
#Iterate through all the subsites in a site collection
foreach ($objWeb in $objWeb.Webs) {
write-host "Site Name::$($objWeb.Title)`t`t Site URL :: $($objWeb.url)" -foregroundcolor green
Get-SPOWebs($objWeb.url)
}
}
catch {
write-host "Could not find web" -foregroundcolor red
}
}
GetSubSiteDetails
<# To run this script you need to set the PowerShell Command-let execution policies as follows
Check the execution policies
Get-ExecutionPolicy -List
Step 2 Set the execution policy to "RemoteSigned" with the below command
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Step 3 Execute the PS1
Step 4 remove the execution policies
Set-ExecutionPolicy Undefined -Scope LocalMachine
#>

The above script has made my life simply and smooth. The output will be as follows:

Get Subsites of a SharePoint Online Site Collection using PowerShell

This PowerShell SharePoint Online tutorial explains how to retrieve all subsites under a site collection using PowerShell in SharePoint Online Office 365.

Here we checked, how to retrieve all the subsites from a site collection using .Net client object model (csom) code. It will display all the subsites other than the SharePoint hosted add-in subsites.

Create SharePoint Site using Rest API

Let us see, how to create a SharePoint site using Rest API. Also, we will check how to delete a SharePoint site using Rest API in SharePoint Online or SharePoint 2013/2016.

We can create a SharePoint site using Rest API in SharePoint Online Office 365. This will also work fine with SharePoint 2013 and SharePoint 2016.

Here we have taken two textboxes where the user can put the SharePoint site name and the site description and a submit button. On click of that, the SharePoint site will get created.

The html code looks like below:

<div id="CreateSite">
<div>
<strong>Site Name:</strong>
<br />
<input type="text" id="txtSiteTitle" />
</div>
<br />
<div>
<strong>Site Description:</strong>
<br />
<textarea cols="20″ id="txtSiteDescription"></textarea>
</div>
<br />
<input type="button" id="btnSubmit" value="Create Site" />
</div>
<div id="divResults"></div>

Here divResults will display the successfull message after the site got created successfully.

Then the script code will be like below. Here in the createSite() method we are retrieving the site title and description from the textboxes and we are making the site URL by removing the space from the title. Other properties which were required to create a site, we have hardcoded inside the __metadata.

The whole code we have added inside a Script editor web part or in content editor web part, inside a web part page.

Rest API Code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
$(function () {
bindButtonClick();
});

function bindButtonClick() {
$("#btnSubmit").on("click", function () {
createSite();
});
}

function createSite() {
var newSiteTitle = $("#txtSiteTitle").val();
var newSiteDesc = $("#txtSiteDescription").val();
var newSiteUrl = newSiteTitle.replace(/\s/g, "");
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/webinfos/add";
$.ajax({
url: fullUrl,
type: "POST",
data: JSON.stringify({
'parameters': {
'__metadata': { 'type': 'SP.WebInfoCreationInformation' },
'Url': newSiteUrl,
'Title': newSiteTitle,
'Description': newSiteDesc,
'Language': 1033,
'WebTemplate': 'sts#0',
'UseUniquePermissions': false
}

}),

headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onQuerySucceeded,
error: onQueryFailed
});
}

function onQuerySucceeded() {
$("#divResults").html("Site Created Successfully!");
}

function onQueryFailed(sender, args) {
alert('Error!');
}
</script>

Once you will Save the page and the page looks like below. Here put a title for the site and a description for the site. Then click on the Submit button. It will show a successful message once the site got created successfully.

create sharepoint site using rest api
create sharepoint site using rest api

You can navigate to the Site Contents page and you can see the site got created successfully.

create sharepoint online site using rest api
create sharepoint online site using rest api

Delete SharePoint Site using Rest API

Now we will see how we can delete a site using Rest API in SharePoint Online Office 365. The same code we can use to delete a site using Rest API in SharePoint 2013/2016.

Here in this example, we are going to take a textbox and a button. The user can put the site title in the textbox and can click on the button to delete the site. The HTML code looks like below and the div with id divResults will display the successful message when the site will get deleted successfully.

HTML Code:

<div id="DeleteSite">
<div>
<strong>Enter Name of Site to Delete:</strong>
<br />
<input type="text" id="txtSiteTitle" />
</div>
<br />
<input type="button" id="btnSubmit" value="Delete Site" />
</div>
<div id="divResults"></div>

Rest API Code:

Below is the Rest API code, here we have taken the site from the textbox. Let us added the full HTML and rest API code inside a script editor web part. You can also use a content editor web part. For this example let us put inside a script editor web part in a web part page.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});

function bindButtonClick() {
$("#btnSubmit").on("click", function () {
deleteSite();
});
}

function deleteSite() {
var siteTitle = $("#txtSiteTitle").val();
var siteTitleNoSpaces = siteTitle.replace(/\s/g, "");
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/" + siteTitleNoSpaces + "/_api/web";
$.ajax({
url: fullUrl,
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "DELETE",
"IF-MATCH": "*"
},

success: onQuerySucceeded,
error: onQueryFailed
});
}

function onQuerySucceeded() {
$("#divResults").html("Site deleted successfully !");
}

function onQueryFailed(sender, args) {
alert('Error!');
}

</script>

Once you save the page, the form will appear like below, where users can put the title and click on the Delete Site button. If the site will get deleted successfully, it will show a successful message like below:

delete sharepoint online site using rest api
delete sharepoint online site using rest api

Now if you will check the SharePoint Site Contents page, you can see the site will not be there.

delete sharepoint site using rest api
delete sharepoint site using rest api

Here, we saw, how to create SharePoint site using rest api and how to delete SharePoint site using Rest API.

Create a SharePoint site using JavaScript

Let us check now, how to create a SharePoint site using JavaScript Object Model (JSOM).

First, let us discuss how we to create a site using the JavaScript Object Model (jsom) in SharePoint Online or SharePoint 2013/2016.

Here I have created an HTML form, where I have added 3 textboxes and one submit button. In those textboxes, the user will enter the SharePoint site title, description, and site template.

Once the user puts that information and click on OK, it will create the SharePoint site and it will show a successful message.

Here we will put the JSOM code as well as the HTML code inside a script editor web part or content editor web part which we will add inside a web part page in SharePoint.

HTML Code:

<div id="CreateSite">
<div>
<strong>Name of Site:</strong>
<br />
<input type="text" id="txtSiteTitle" />
</div>
<br />
<div>
<strong>Description of Site:</strong>
<br />
<textarea cols="20" id="txtSiteDescription"></textarea>
</div>
<div>
<br />
<strong>Site Template:</strong>
<br />
<input type="text" id="txtSiteTemplate" />
</div>
<br />
<input type="button" id="btnSubmit" value="Create Site" />
</div>
<div id="divResults"></div>

JSOM Code:

Here we are calling the createSite() method in the button click event. To create a SharePoint site we also need to provide the site URL, which we can take from the title.

We are getting the site URL by removing the space from the site title textbox.

var siteUrl = siteTitle.replace(/\s/g, "");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});
function bindButtonClick() {
$("#btnSubmit").on("click", function () {
createSite();
});
}

function createSite() {
var siteTitle = $("#txtSiteTitle").val();
var siteDesc = $("#txtSiteDescription").val();
var siteUrl = siteTitle.replace(/\s/g, "");
var siteTemplate = $("#txtSiteTemplate").val();
var clientContext = new SP.ClientContext();
var collWeb = clientContext.get_web().get_webs();
var webCreationInfo = new SP.WebCreationInformation();
webCreationInfo.set_title(siteTitle);
webCreationInfo.set_description(siteDesc);
webCreationInfo.set_language(1033);
webCreationInfo.set_url(siteUrl);
webCreationInfo.set_useSamePermissionsAsParentSite(true);
webCreationInfo.set_webTemplate(siteTemplate);
var oNewWebsite = collWeb.add(webCreationInfo);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed)
);
}

function onQuerySucceeded() {
$("#divResults").html("Site successfully created!");
}

function onQueryFailed(sender, args) {
alert(‘Request failed. ‘ + args.get_message() +‘\n’ + args.get_stackTrace());
}

</script>

Once you will save the SharePoint web part page, you can see the site creation form will look like below. Here user can put SharePoint site name, description and template like below. On successful creation it will display the message like below:

create sharepoint site programmatically javascript
create sharepoint site programmatically javascript

Now if you will go to the SharePoint site contents and then under subsites section, you can see the subsite got created successfully.

create sharepoint site jsom
create sharepoint site jsom

Here, we learned, how to create a site using jsom in SharePoint Online as well as SharePoint 2016/2013.

Delete SharePoint Site using JavaScript Object Model (JSOM)

Now we will see how to delete a SharePoint site using the JavaScript object model (jsom) in SharePoint Online/2013/2016.

Here I have created an HTML form and in the form, I have added a textbox where the user can put the SharePoint site title in the textbox and the user can click on submit button.

Once click on the submits button it will delete the site and on successful deletion, it will display a successful message to the user.

HTML Code:

<div id="DeleteSite">
<div>
<strong>Site Name to delete:</strong>
<br />
<input type="text" id="txtSiteTitle" />
</div>
<br />
<input type="button" id="btnSubmit" value="Delete Site" />
</div>
<div id="divResults"></div>

JSOM Code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});
function bindButtonClick() {
$("#btnSubmit").on("click", function () {
deleteSite();
});
}

function deleteSite() {
var siteTitle = $("#txtSiteTitle").val();
var siteTitleNoSpaces = siteTitle.replace(/\s/g, "");
var siteUrl = _spPageContextInfo.webAbsoluteUrl + "/" + siteTitleNoSpaces;
var clientContext = new SP.ClientContext(siteUrl);
var oWebsite = clientContext.get_web();
oWebsite.deleteObject();
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed)
);
}

function onQuerySucceeded() {
$("#divResults").html("Site successfully deleted!");
}

function onQueryFailed(sender, args) {
alert(‘Request failed. ‘ + args.get_message() +
‘\n’ + args.get_stackTrace());
}

</script>

Once you Save the SharePoint page, you can see the page like below, where user can put the site title and you can see on successful deletion it is displaying a successful message.

jsom delete sharepoint subsite
jsom delete sharepoint site

Now if you will go and see the SharePoint site contents page, in subsites section you will not see the site, because it is already got deleted.

Delete SharePoint Site using JavaScript

Here, we checked how to delete a SharePoint site using the JavaScript Object Model (jsom) in SharePoint Online/2013/2016.

Change Search Center URL using JavaScript in SharePoint

Let us see, how to change the search center URL in SharePoint Online/2013/2016 using JavaScript object model code (jsom).

To change the search center URL using browser we can navigate to Open SharePoint Online Site Settings -> then click on “Search Settings” which is under “Site Collection Administration”.

By default it will be blank like below:

Change Search Center URL using JavaScript in SharePoint
Change Search Center URL using JavaScript in SharePoint

Change Search Center URL using JavaScript in SharePoint

Now we will see how to change the search center URL in SharePoint 2013 using JSOM (JavaScript Object Model).

Here let us take a button and on click of that button, we will change the search center URL. Both the HTML and JSOM code we have written inside a script editor web part which is inside a web part page.

We can set the SRCH_ENH_FTR_URL_SITE property which will change the search center URL.

<input type="button" id="btnSubmit" value="Set Search URL" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});

function bindButtonClick() {
$("#btnSubmit").on("click", function () {
setSearchURL();
});
}

function setSearchURL() {
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_site().get_rootWeb();
var props = web.get_allProperties();
props.set_item("SRCH_ENH_FTR_URL_SITE", "/sites/Bhawana/MySearchCenter");
web.update();
ctx.load(web);
ctx.executeQueryAsync(function () {
alert("Search Settings Modified");
},

function () {
alert("failed");
});
}
</script>

Once you Save the code and click on the button, the search center URL will be changed like below:

change search center url using javascript sharepoint
Change Search Center URL using JavaScript in SharePoint

You may like the following SharePoint site collection tutorials:

I hope this SharePoint tutorial explains, how to create a SharePoint site or subsite in SharePoint Online.

  • Create site in SharePoint Online or SharePoint 2013/2016/2019
  • Create subsite in SharePoint 2013 Online programmatically using CSOM
  • SharePoint Check if subsite exists using CSOM
  • Create subsite in SharePoint Online programmatically
  • Create subsite in SharePoint programmatically using server object model
  • Create subsite in SharePoint programmatically using csom (client side object model)
  • Delete sites and subsites programmatically using CSOM in SharePoint Online
  • Get all subsites from a site collection in SharePoint Online using CSOM
  • Get all subsites from a site collection in SharePoint using CSOM
  • Get Subsites of a SharePoint Online Site Collection using PowerShell
>