1

According to the documentation surroundContents() surrounds a selected node. The docu mentions

An exception will be thrown, however, if the Range splits a non-Text node with only one of its boundary points. That is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail.

What I didn't find is if there is a way to check before if the exception would occur or not. i.e. How to check before executing the operation if the action is possible?

Use case: The user shouldn't be able to perform the action if its not possible.

I know that I can try catch the action and prevent that to be happen. But checking before would be great.

Initially I thought about checking if the elements in the Range.startContainer and Range.endContainer have some block element - but this won't help much. Especially since checking block element sounds tricky. range.cloneRange() doesn't help much either. Any other ideas?

LeO
  • 4,238
  • 4
  • 48
  • 88
  • Do you have some example code you're working with? Providing a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) demonstrating the problem will probably yield more response. – pilchard Oct 23 '22 at 08:58
  • Don't know what kind of code to provide. In the initial link a code is provided. Basically it must be some check on the selected nodes - but don't know how to check the selected Range. – LeO Oct 23 '22 at 11:57
  • Some duplicates: [How can i get all text nodes inside a dom range?](https://stackoverflow.com/questions/7685753/how-can-i-get-all-text-nodes-inside-a-dom-range), [Use javascript to extend a DOM Range to cover partially selected nodes](https://stackoverflow.com/questions/2477192/use-javascript-to-extend-a-dom-range-to-cover-partially-selected-nodes), [InvalidStateError: Failed to execute 'surroundContents' on 'Range': The Range has partially selected a non-Text node](https://stackoverflow.com/questions/67634286/invalidstateerror-failed-to-execute-surroundcontents-on-range-the-range-ha) – pilchard Oct 23 '22 at 12:30
  • heres a [jsfiddle](https://jsfiddle.net/1t8ve7dn/3/) as a base for testing against. – pilchard Oct 23 '22 at 12:38

1 Answers1

0

Just for the sake of documentation: I found the following solution:

try {
// check if the browser allows a surround ==> than surround it
    const testRange = selection.getRng().cloneRange();
    testRange.surroundContents(document.createElement('span'));
    // .... perform action 
} catch (error) {
    //surrounding not possbile
}

Honestly I dislike the solution since it needs to raise an error (and then catch it). But if somebody else has a better idea I'm curious.

LeO
  • 4,238
  • 4
  • 48
  • 88