Get URL of all Sub-sites using CSOM

Many a times we need to list all the sub-sites underneath of current site and sometimes sub-sites from the root site. Here, we will display the site URL of all the sub-site underneath of current site.

When you are working with SharePoint on-prem, you have option to use Table of Content web-part which do the exactly same thing.

Let’s start, I am using SharePoint online for this demo. And I’ll put all the code inside the “Content Editor” web-part.

Here is the code which you can use.

/Projects/SiteAssets/jquery-1.11.3.min.js

SP.SOD.executeFunc(‘sp.js’, ‘SP.ClientContext’, function(){
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var siteColl = context.get_site();
var webSubSites = web.get_webs();

context.load(webSubSites, ‘Include(Title, ServerRelativeUrl)’);

context.executeQueryAsync(
Function.createDelegate(this, function (sender, args) {

for (var x = 0; x < webSubSites.get_count(); x++) {
var subWeb = webSubSites.itemAt(x);
console.log(subWeb.get_serverRelativeUrl());
}

}),
Function.createDelegate(this, function (sender, args) {
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}));

});

I am writing all the output to console. You can use the output as per your need.

Enjoy!

Leave a comment