7

For the question lets assume the following site hierarchy

  • Root Site
    • Sub Site 01
      • Sub Site 0101
      • Sub Site 0102
        • Sub Site 010201
    • Sub Site 02
    • Sub Site 03
      • Sub Site 0301

Now if I want to get all these sub site object in an array, what would be the best approach.

PS - rootWeb.get_webs() would return me just the immediate child sub sites. This would require me the make a recursive async call to each child sub site to get further down the hierarchy. I m guessing this will have performance issues and callback challenges.

9

How to retrieve all web sites under a site collection using SharePoint JSOM

The following function demonstrates how to recursively retrieve all sub sites:

function getAllWebs(success,error)
{
   var ctx = SP.ClientContext.get_current();
   var web = ctx.get_site().get_rootWeb();
   var result = [];
   var level = 0;
   var getAllWebsInner = function(web,result,success,error) 
   {
      level++;
      var ctx = web.get_context();
      var webs = web.get_webs(); 
      ctx.load(webs,'Include(Title,Webs)');
      ctx.executeQueryAsync(
        function(){
            for(var i = 0; i < webs.get_count();i++){
                var web = webs.getItemAtIndex(i);
                result.push(web);
                if(web.get_webs().get_count() > 0) {
                   getAllWebsInner(web,result,success,error);
                }   
            }
            level--;
            if (level == 0 && success)
              success(result);  
        },
        error);
   };

   getAllWebsInner(web,result,success,error);    
}

getAllWebs.js

Usage

getAllWebs(
function(allwebs){
    for(var i = 0; i < allwebs.length;i++){
        console.log(allwebs[i].get_title());   
    }
},
function(sendera,args){
    console.log(args.get_message());
});
  • Short of writing your own endpoint to expose the AllWebs property of the SPSite object, this recursion is the best/only way - so you should probably avoid it if your site is too nested and load the sub sites on demand – Choggo Feb 2 '15 at 13:10
  • @Choggo I agree with your comment about the highly nested site hierarchy. This is my concern. I was wondering if there is any better way to get all sub site under a site (read as web). Just a thought, Will search api suit better? – bkk Feb 3 '15 at 12:22
  • 1
    The search API is a good idea (but has a limit of 500 items per page - might not be a problema). If you are on premise, you can write a REST service to return the information for you, as well. – Choggo Feb 3 '15 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.