2

Do you know how to get the current web part Id with the javascript client OM API ?

Or an idea for a work-around ?

Thanks

2

Your Web Part will have an element attribute called webpartid so you can use this to select all Web Parts, like this (jQuery):

$('[webpartid]');

To select your own specific Web Part you could add something specific in the markup you can use to select it, for example an empty/hidden element with a specific class, like <span class="my-hack"></span>, then your Web Part can be selected like this (jQuery):

$('[webpartid]:has(.my-hack)');
 // or
$('.my-hack');
// or
$('.my-hack').closest('[webpartid]');
  • thx ! Do you know a way to access a specific instance (in the case where there are more than one instances of this web part in a page) ? – Dino Sep 27 '12 at 8:04
  • That is what the .my-hack is for, something within the markup that tells you it is your Web Part. You could also use the Title, but this is dangerous as the title can be removed (Chrome Frame Type). In theory: $('[webpartid]:has(.my-hack)').each(function(){ var $myWP = $(this); ... }); – eirikb Sep 27 '12 at 8:08
  • it didn't worked for me, I had to get it with : $('.someClass').parents('.ms-WPBody').attr('webpartid'); – Dino Sep 27 '12 at 12:58
  • The one I used with .closest should work, it reads as > "recursive parent of your element (.my-hack) with attribute 'webpartid' defined" – eirikb Sep 27 '12 at 13:00
  • So this will not work if you have an instance of the same webpart with a hidden .my-hack in it. Example: think of an image slider, but you want to get image list from the weppart property. On $().ready() if you try to find $('.my-hack').closest('[webpartid]'); it will always bring back the first webpart and not the webpart where the script was called from. Any solutions? – dotsa Jan 5 '15 at 21:02
0

you can select it by position or title and then retrieve the id with JSOM, here is an example based on position:

function GetWPInfo()
{
    var currentCtx = SP.ClientContext.get_current();
    var pageFile = currentCtx.get_web().getFileByServerRelativeUrl(_spPageContextInfo.serverRequestPath);
    var webPartManager = pageFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
    var webPartDefs = webPartManager.get_webParts();
    currentCtx.load(webPartDefs, 'Include(Id)');
    currentCtx.executeQueryAsync(
    function () {
        if (webPartDefs.get_count()) {
                var webPartDef = webPartDefs.getItemAtIndex(1);
                alert(webPartDef.get_id());
        }
        else {
            console.log("No web parts found.");
        }
    },
    function (sender, args) {
        console.log(args.get_message());
    });
}

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.