You'll need to use some JavaScript in any case, so my suggestion would be to simply modify the <<replace>> macro itself. It's easy enough; just replace its handler() method in your story's JavaScript portion.
Macro.get("replace").handler = function() {
if (this.args.length === 0) {
return this.error('no selector specified');
}
if (this.payload[0].contents !== '') {
const $targets = jQuery(this.args[0]);
const frag = document.createDocumentFragment();
new Wikifier(frag, this.payload[0].contents);
switch (this.name) {
case 'replace':
$targets.empty().append(frag);
break;
case 'append':
$targets.append(frag);
break;
case 'prepend':
$targets.prepend(frag);
break;
}
} else if (this.name === 'replace') {
jQuery(this.args[0]).empty();
}
};
What it does, in comparison to the original macro handler, is simply removing the check for "no valid targets found", or those three lines:
if ($targets.length === 0) {
return this.error(`no elements matched the selector "${this.args[0]}"`);
}
I also compressed the code a bit, but that's purely æsthetics.