I want to be able to retrieve items from a subsite. I've found some code which works but only on the current site.

<script type="text/javascript">

ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"); 

var objContext = null; 
var objWeb = null     
var objList = null;
var objItem = null;

    function MainFunction() {   
        objContext = new SP.ClientContext.get_current();
        objWeb = objContext.get_web();   
        objList = objWeb.get_lists().getByTitle("testList");


        objContext.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFail));   

    function onSuccess(sender, args) {
        alert('Item Count: ' + objList.get_itemCount());

    function onFail(sender, args) {   
        alert('Some error has occured.');   

How can I modify this to work on sub sites?

1 Answer 1


You have to specify the URL to new SP.ClientContext(url)

From MSDN:

var url = 'replace with server-relative or absolute URL';
var clientContext;
var website;

// Make sure the SharePoint script file 'sp.js' is loaded before your
// code runs.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);

// Create an instance of the client context for the specified URL.
function sharePointReady() {
    clientContext = new SP.ClientContext(url);
    website = clientContext.get_web();

    clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);
function onRequestSucceeded() {
    alert('URL of the website: ' + website.get_url());
function onRequestFailed(sender, args) {
    alert('Error: ' + args.get_message());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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