9

How can we get an immediate parent web of a subsite using JSOM ?

1
  • I am assuming you mean CSOM (Client Side Object Model). Commented Mar 31, 2016 at 18:09

4 Answers 4

13
+100

Using your SP.Web object, you can get the parent information (SP.WebInformation). Using its ID, you can then, via the site collection, get the parent web object.

var context = new SP.ClientContext.get_current();        
var web = context.get_web();                       
var parentInfo = web.get_parentWeb();  
var parentWeb = context.get_site().openWebById(parentInfo.get_id());

context.load(parentInfo);
context.load(parentWeb);

context.executeQueryAsync(Function.createDelegate(this,onListDataSucceeded),Function.createDelegate(this, onListDataFailed)); 

function onListDataSucceeded(sender, args)
{
    alert(this.parentWeb.get_title());
}

function onListDataFailed(sender, args)
{
    alert('error');
}

Methods used:

4
  • 1
    Also worth mentioning: the WebInformation object returned from get_parentWeb is also useful in many ways if you don't need to do further manipulation to the web object; it gives you access to the parent web title, server relative url, id, etc.
    – John-M
    Commented Mar 31, 2016 at 19:14
  • And also - I would add another plus 1 for the link to the definitely typed API reference, I didn't know about that version and it's much nicer than the MSDN reference
    – John-M
    Commented Mar 31, 2016 at 19:21
  • 1
    Shouldn't you execute the query to get the id from the parentWeb before you use it, so one will need two calls. Other than that it looks good :) Commented Mar 31, 2016 at 21:34
  • Anything for SharePoint 2010? Alternative to get_parentWeb()? Commented Jan 9, 2018 at 11:56
6

An alternative to using the get_parentWeb is using the _spPageContextInfo object for urls and only needs one execute:

if(_spPageContextInfo.siteServerRelativeUrl != _spPageContextInfo.webServerRelativeUrl) {

  var parentWebUrl = _spPageContextInfo.webServerRelativeUrl.split("/").slice(0,-1).join("/");
  var ctx = new SP.ClientContext(parentWebUrl);
  var web = ctx.get_web();
  ctx.load(web, "Title");
  ctx.executeQueryAsync(function() {
    console.log(web.get_title());
  }, function(sender, args) {
    console.log("Err: " + args.get_message());
  }) 
}

Works in Office 365, tbh I'm not updated on the _spPageContextInfo object on prem, and what is available on it these days.

0
5

Using REST API, it is very much easier to get parent web information. Just make a GET request to the following URL.

_api/Web/ParentWeb

In response, you will get all information about parent as like following.

{
  "d": {
    "__metadata": {
      "id": "http://xxx.sharepoint.com/_api/Web/ParentWeb",
      "uri": "http://xxx.sharepoint.com/_api/Web/ParentWeb",
      "type": "SP.WebInformation"
    },
    "Configuration": 0,
    "Created": "2016-01-04T10:59:47",
    "Description": "Parent site description",
    "Id": "495add3e-4b0c-485c-941b-d28130ef18c8",
    "Language": 1033,
    "LastItemModifiedDate": "2016-03-31T13:13:50Z",
    "ServerRelativeUrl": "/sites/parentSite",
    "Title": "Parent Site Title",
    "WebTemplate": "STS",
    "WebTemplateId": 0
  }
}

Example Using pure JavaScript

function getParentWeb() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.open("GET", _spPageContextInfo.webAbsoluteUrl + '/_api/Web/ParentWeb');

    xmlhttp.setRequestHeader("Accept", "application/json;odata=verbose");

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
            if (xmlhttp.status == 200) {

                var response = JSON.parse(xmlhttp.responseText);
                var parentWeb = response.d;
                console.log(parentWeb); // parent web is here.


            } else {
                alert('Error: ' + xmlhttp.statusText)
            }
        }
    }

    xmlhttp.send();
}

Example using jQuery

function getParentWeb() {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + '/_api/Web/ParentWeb',
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function(data) {
            var parentWeb = response.d;
            console.log(parentWeb); // parent web is here.
        },
        error: function(error) {
            alert(JSON.stringify(error));
        }
    });
}
0

You can also directly use the _spPageContextInfo.siteAbsoluteUrl property to get the url of the root web in the site collection.

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.