1

How would I check in javascript if web part zones have no web parts?

Thanks

1 Answer 1

1

You can check if a page has some webparts or not.

var siteUrl = '/sites/MySiteCollection';
var serverRelativeUrl = '/sites/MySiteCollection/Default.aspx';

function updateWebPartTitle() {    
    this.clientContext = new SP.ClientContext(siteUrl);
    var oFile = clientContext.get_web().getFileByServerRelativeUrl(serverRelativeUrl);    
    var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
    this.collWebPart = limitedWebPartManager.get_webParts();    
    clientContext.load(collWebPart);    
    clientContext.executeQueryAsync(Function.createDelegate(this, this.SuccessFunc), Function.createDelegate(this, this.onQueryFailed));
}

function SuccessFunc() {    
    if (!collWebPart.get_count()) {
        alert('No Web Parts on this page.');
    }         
}    

function onQueryFailed(sender, args) {    
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Check MSDN source here.

Update:

If you know the webpartzone id and try something like this.

<div class="inner"> 
<WebPartPages:WebPartZone id="zone1"><ZoneTemplate></ZoneTemplate></WebpartPages:WebPartZone> 
</div>

then query the zone and see it has table element because generally webpart will be rendered in a table.

if($('#zone1').find('table').length != 0){
        //webpart exists
}

You may need to adjust your code based on actual dom.I can not test it now.

4
  • Its not about checking if a page has web parts, its about if a specific zone has any web parts using only DOM checking with javascript, and no ajax calls.
    – omega
    Commented Oct 7, 2016 at 15:19
  • @omega then probably you have to inspect the zone area by F12 and check for descendant element length is 0 or not using js.And to me this will be a bad idea.
    – user13408
    Commented Oct 7, 2016 at 15:22
  • I need it to be in js, and was wondering if anyone has this code already.
    – omega
    Commented Oct 7, 2016 at 15:23
  • @omega try the updates I posted.
    – user13408
    Commented Oct 7, 2016 at 15:42

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.