Create subsite and page using javascript in SharePoint Online/2013/2016

This SharePoint tutorial explains, how to create a subsite and page using JavaScript (javascript object model) in SharePoint 2016/2013 or SharePoint online.

Here we will use the below code inside a script editor web part inside a web part page in the SharePoint site.

Create subsite and page using javascript in SharePoint

Here, I have created an HTML textbox and a button where the user will provide a site name and click on the button to create a subsite and page using the JavaScript object model (jsom) in SharePoint 2013/2016 or SharePoint Online.

Title: <input type="text" id="txtSitename" /> &nbsp <button type="button" id="btnCreateSite" >Create</button>

<script type="text/javascript" src="/sites/Intranet/Style%20Library/aaa/jquery-1.8.3.min.js" ></script>
<script type="text/javascript" src="/_layouts/15/SP.Runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/SP.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.publishing.js"></script>

<script type="text/javascript">

$("#btnCreateSite").click(function(){
CreateWebsite($("#txtSitename").val(), $("#txtSitename").val(), $("#txtSitename").val(), "BLANKINTERNET#2");
});

var context;
var web;
var newWeb;
function CreateWebsite(title, description, webUrl, templateTitle)
{
context = new SP.ClientContext.get_current();
web = context.get_web();
context.load(web);
var webTemplates = web.getAvailableWebTemplates(1033,false);
context.load(webTemplates);
context.executeQueryAsync(function(){
var enumerator = webTemplates.getEnumerator();
var customTemplate;
while(enumerator.moveNext())
{
var webTemplate = enumerator.get_current();
var webTitle = webTemplate.get_title();
if(webTitle == templateTitle)
{
customTemplate = webTemplate.get_name();
break;
}
}
var webCreationInformation = new SP.WebCreationInformation();
webCreationInformation.set_title(title);
webCreationInformation.set_description(description);
webCreationInformation.set_language(1033);
webCreationInformation.set_url(webUrl);
webCreationInformation.set_useSamePermissionsAsParentSite(true);
webCreationInformation.set_webTemplate(customTemplate);
newWeb= web.get_webs().add(webCreationInformation);
context.executeQueryAsync(function(){
createPublishingPage("Home.aspx", "blankWebPartPage.aspx")
alert('Website created successfully.');
},
function(sender, args){
alert(args.get_message());
});
},
function(sender, args){
alert(args.get_message())
}
);
}

function loadPageLayout (pageLayoutName, callback) {
var pageFromDocLayout, pageLayoutItem;

SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function () {
context = SP.ClientContext.get_current();
var site = context.get_site();

context.executeQueryAsync(function () {
var rootWeb = site.get_rootWeb();
context.load(rootWeb, 'ServerRelativeUrl');

context.executeQueryAsync(function () {
var rootUrl = rootWeb.get_serverRelativeUrl();
pageFromDocLayout = rootWeb.getFileByServerRelativeUrl(rootUrl + "_catalogs/masterpage/" + pageLayoutName);

context.executeQueryAsync(function () {
pageLayoutItem = pageFromDocLayout.get_listItemAllFields();

context.executeQueryAsync(function () {
if (typeof callback == "function") {
callback(pageLayoutItem);
}
});
});
});
});
});
};

function createPublishingPage (filename, pageLayoutName, callback) {
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function () {
SP.SOD.executeFunc('SP.Publishing.js', 'SP.Publishing.PublishingWeb', function () {
var pubWeb, pageInfo, newPage, listItem;
//context = new SP.ClientContext('/sites/Intranet');

//web = currWeb;
context.load(newWeb);
context.executeQueryAsync(function () {
pubWeb = SP.Publishing.PublishingWeb.getPublishingWeb(context, newWeb);
context.load(newWeb);
context.load(pubWeb);
context.executeQueryAsync(function () {

// load page layout and create the new page
loadPageLayout(pageLayoutName, function (pageLayoutItem) {
pageInfo = new SP.Publishing.PublishingPageInformation();
pageInfo.set_pageLayoutListItem(pageLayoutItem);
pageInfo.set_name(filename);

newPage = pubWeb.addPublishingPage(pageInfo);

context.load(newPage);

context.executeQueryAsync(function () {
// Success callback after adding a new Publishing Page.
// We want to get the actual list item that is represented by the Publishing Page.
listItem = newPage.get_listItem();
context.load(listItem);

context.executeQueryAsync(

// Success callback after getting the actual list item that is
// represented by the Publishing Page.
// We can now get its FieldValues, one of which is its FileLeafRef value.
// We can then use that value to build the Url to the new page
// and set the href or our link to that Url.
function () {
if (typeof callback == "function") {
callback(listItem);
}
},

// Failure callback after getting the actual list item that is
// represented by the Publishing Page.
function (sender, args) {
alert('Failed to get new page: ' + args.get_message());
}
);
},
// Failure callback after trying to add a new Publishing Page.
function (sender, args) {
alert('Failed to Add Page: ' + args.get_message());
}
);
});
},
// Failure callback after trying to get the host Web as a PublishingWeb.
function (sender, args) {
alert('Failed to get the PublishingWeb: ' + args.get_message());
});
});
});
});

}

</script>

Create SharePoint Subsite using JavaScript

Now, let us see how to create a SharePoint subsite using jQuery and JavaScript client object model in SharePoint 2016, SharePoint 2013 or SharePoint Online.

We will also see, how to get all SharePoint subsites using the JavaScript object model (jsom).

The code will work in SharePoint 2016/2013 and SharePoint Online also. You can directly put the below code inside a script editor web part on a web part page in SharePoint.

Create SharePoint Sub Site using JSOM

As you can see here I am taking one textbox and I am using the value for the site name, description as well as the URL.

<h1>Create Site</h1>

Site Name: <input type="text" name="txtSitename" id="txtSitename">
<input type="submit" value="Submit" id="btnCreateSite">

<script type="text/javascript">

$("#btnCreateSite").click(function(){
CreateWebsite($("#txtSitename").val(), $("#txtSitename").val(), $("#txtSitename").val(), "BLANKINTERNET#2");
});

function CreateWebsite(title, description, webUrl, templateTitle)
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
context.load(web);
var webTemplates = web.getAvailableWebTemplates(1033,false);
context.load(webTemplates);
context.executeQueryAsync(function(){
var enumerator = webTemplates.getEnumerator();
var customTemplate;
while(enumerator.moveNext())
{
var webTemplate = enumerator.get_current();
var webTitle = webTemplate.get_title();
if(webTitle == templateTitle)
{
customTemplate = webTemplate.get_name();
break;
}
}
var webCreationInformation = new SP.WebCreationInformation();
webCreationInformation.set_title(title);
webCreationInformation.set_description(description);
webCreationInformation.set_language(1033);
webCreationInformation.set_url(webUrl);
webCreationInformation.set_useSamePermissionsAsParentSite(true);
webCreationInformation.set_webTemplate(customTemplate);
var newWeb= web.get_webs().add(webCreationInformation);
context.executeQueryAsync(function(){
alert(‘Website created successfully.’);
},
function(sender, args){
alert(args.get_message());
});
},
function(sender, args){
alert(args.get_message())
}
);
}
</script>

The form will look like below:

Create SharePoint Sub Site using JSOM
Create SharePoint Sub Site using JSOM

Give a name and click on Submit button which will create a sub site under the site.

Get all SharePoint subsites using JavaScript

Now, we will see how to get all SharePoint subsites using JavaScript object model (jsom).

To use the code, create a web part page and a content editor webpart or script editor web part and add the below code.

<script>
ExecuteOrDelayUntilScriptLoaded(RetriveSites,"sp.js");
function RetriveSites()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
//this.subsites = currentweb.get_webs();
this.subsites = currentweb.getSubwebsForCurrentUser(null);
currentcontext.load(this.subsites);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}

function ExecuteOnSuccess(sender, args) {
var subsites = ";
var enum1 = this.subsites.getEnumerator();
var el = document.getElementById(‘LKMSubWebs');
while (enum1.moveNext())
{
var Site = enum1.get_current();
subsites += ‘\n' + ‘<a class=subsitecls href='+ Site.get_serverRelativeUrl()+'>'+Site.get_title()+'</a> </br>'
//RootElement.append(‘<a class=subsitecls href='+ siteTitle+'>'+siteTitle+'</a> </br>');
//alert(subsites);
}
el.innerHTML = subsites;
}

function ExecuteOnFailure(sender, args) {
alert("error");
//alert(args.get_message());
}
</script>

<div id="LKMSubWebs"></div>

This will bind all the SharePoint subsites titles and will display them.

You may like following jsom SharePoint tutorials:

This jsom sharepoint tutorial explains, how to create a subsite and page using jsom (JavaScript object model) in SharePoint Online or SharePoint 2013/2016.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>