Once the script runs successfully, your lookup column will be connected to the new list, and you’ll see the correct source in the column settings



(function updateLookupFieldSchema() {
const listWithLookupUrl = 'https://m365x46891638.sharepoint.com/sites/ContractManagement/Lists/Contracts';
const lookupFieldName = 'LookupToAccounts';
const lookupSourceListUrl = 'https://m365x46891638.sharepoint.com/sites/ContractManagement/Lists/Accounts';

const targetUrlObj = new URL(listWithLookupUrl);
const sourceUrlObj = new URL(lookupSourceListUrl);
const targetListSR = targetUrlObj.pathname;
const sourceListSR = sourceUrlObj.pathname;

const targetWebUrl = extractSiteUrl(listWithLookupUrl);
const sourceWebUrl = extractSiteUrl(lookupSourceListUrl);

const ctxTarget = new SP.ClientContext(targetWebUrl);
const webTarget = ctxTarget.get_web();
const listTarget = webTarget.getList(targetListSR);
const field = listTarget.get_fields().getByInternalNameOrTitle(lookupFieldName);

ctxTarget.load(field, 'SchemaXml', 'Id');
ctxTarget.executeQueryAsync(onFieldLoaded, onError.bind(null, 'Load field'));

function onFieldLoaded() {
const xmlDoc = new DOMParser().parseFromString(field.get_schemaXml(), 'application/xml');
const fieldNode = xmlDoc.getElementsByTagName('Field')[0];

const ctxSrc = (sourceWebUrl === targetWebUrl)
? ctxTarget
: new SP.ClientContext(sourceWebUrl);
const webSource = ctxSrc.get_web();
const listSource = webSource.getList(sourceListSR);

ctxSrc.load(listSource, 'Id');
if (sourceWebUrl !== targetWebUrl) {
ctxSrc.load(webSource, 'Id');
}

ctxSrc.executeQueryAsync(function () {
const listIdBraced = '{' + listSource.get_id().toString().toUpperCase() + '}';
fieldNode.setAttribute('List', listIdBraced);

if (sourceWebUrl !== targetWebUrl) {
fieldNode.setAttribute('WebId', webSource.get_id().toString().toUpperCase());
} else {
if (fieldNode.hasAttribute('WebId')) {
fieldNode.removeAttribute('WebId');
}
}

// fieldNode.setAttribute('ShowField', 'InternalNameOfYourColumn');

const newSchema = new XMLSerializer().serializeToString(xmlDoc);
field.set_schemaXml(newSchema);
field.update();

ctxTarget.executeQueryAsync(
() => console.log('✅ Lookup field schema updated.'),
onError.bind(null, 'Update field')
);
}, onError.bind(null, 'Load source list'));
}

function extractSiteUrl(listUrl) {
const urlParts = listUrl.split("/");
if (urlParts.length > 1 && urlParts[urlParts.length - 2].toLowerCase() === "lists") {
return urlParts.slice(0, urlParts.length - 2).join("/");
}
return urlParts.slice(0, urlParts.length - 1).join("/");
}

function onError(stage, sender, args) {
console.error(stage + ' error: ' + args.get_message());
}
})();