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
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]');
$('[webpartid]:has(.my-hack)').each(function(){ var $myWP = $(this); ... });
.closest
should work, it reads as > "recursive parent of your element (.my-hack) with attribute 'webpartid' defined"
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());
});
}