List subsites using the JavaScript client object model in SharePoint 2013

SharePoint Office 365 Site Creation JavaScript

To do this, use the script editor web part or the page viewer web part (and put the HTML file in a document library).

To start off, setup the HTML to include jQuery and sp.js (see below).

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {

JQuery functions are used to populate HTML containers on the page.

<div id="tonycontent">
	<!-- Dashboard -->
	<div id="tonydashboard" class="tonycontenttable">

The first function loads the current site. The get_current function returns the current context of the user from which the subsites can be retrieved (see below).

function getSubWebs(){
	clientContext = new SP.ClientContext.get_current();
	web = clientContext.get_web();
    	webCollection = web.getSubwebsForCurrentUser(null);
    	clientContext.executeQueryAsync(onGetSubwebsSuccess, onGetSubwebsFail);

If the query is successful it will load the onGetSubwebsSuccess function, otherwise it will run onGetSubwebsFail function.

In the success function, the webCollection variable is looped through to retrieve the URL and the title of each subsite. JQuery functions are then used to append the HTML containers.

function onGetSubwebsSuccess(sender, args){
	var html4 ="<div class='tonycontenttablerow'><div class='tonycontenttabletitle'>Site Name</div><div class='tonycontenttabletitle'>Site URL</div></div>";
    var webEnumerator = webCollection.getEnumerator();	
    while (webEnumerator.moveNext()){
        var web = webEnumerator.get_current();
		var webtitle = web.get_title();
		var weburl = web.get_serverRelativeUrl();
        var html3="<div class='tonycontenttablerow'><div class='tonycontenttablecolumn'>" + webtitle + "</div><div class='tonycontenttablecolumn'>" + weburl + "</div></div>";

Download the full code here

The client object model can also be used to create subsites from templates, permission sites, create lists and much more! This method works on both 365 SharePoint Online and SharePoint 2010 and SharePoint 2013 on-premises.

SharePoint 2013 JavaScript Client Object Model

Leave a Reply

Your email address will not be published. Required fields are marked *