Tuesday, December 20, 2016

Get All Folders using JavaScript Object Model (ECMA) Programming In SharePoint 2016 And Office 365

Steps:

  • Add Content Editor Web part (CEWP) to the SharePoint page.
  • Save the below script as a text file and upload it to Site Assets page.
  • Refer the script file from the CEWP.

Script:

<script language="javascript" type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
 SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getAllFolders);
});
var oListItem,collListItem,clientContext;
function getAllFolders() {
 //Get client context,web and list object
 clientContext = new SP.ClientContext();
 var oWeb= clientContext.get_web();
 var oList = oWeb.get_lists().getByTitle('Demo Library');
 //use caml query to get the folder collection
 var camlQuery = new SP.CamlQuery();
 camlQuery.set_viewXml("<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef
Name='FSObjType'/><Value Type='Text'>1</Value></Eq></Where></Query></View>");
 camlQuery.set_folderServerRelativeUrl('/Sites/Playground/Demo
Library/NewFolder');
 collListItem = oList.getItems(camlQuery)
 //Load the client context and execute the batch
 clientContext.load(collListItem);
 clientContext.executeQueryAsync(Success, Failure);
}
function Success() {
 //get the folder collection and loop through it
 var listItemEnumerator = collListItem.getEnumerator();
 var oListItem;
 while (listItemEnumerator.moveNext()) {
 oListItem = listItemEnumerator.get_current();
 console.log(oListItem.get_item('FileLeafRef'));
 }
}
function Failure(sender,args) {
 console.log('Request failed with error message - '+ args.get_message()+' .
Stack Trace - '+ args.get_stackTrace());
}
</script>

No comments:

Post a Comment