Skip to content

Instantly share code, notes, and snippets.

@adityabhaskar
Created September 15, 2018 06:50
Show Gist options
  • Save adityabhaskar/895bc1884fcac60f12ab1f6548ad4798 to your computer and use it in GitHub Desktop.
Save adityabhaskar/895bc1884fcac60f12ab1f6548ad4798 to your computer and use it in GitHub Desktop.
Check if selection is a link
const selection = getSelection();
const isALink = selection.type.toLowerCase() == "range") && // Selection is a range, and
selection.anchorNode == selection.focusNode && // Starts & finishes in the same node, and
selection.anchorOffset == 0 && // Starts at beginning of the node, and
selection.focusOffset == selection.focusNode.textContent.length && // Finishes at end of the node, and
(selection.anchorNode.nodeName.toLowerCase() == 'a' || // Node is of type 'a' (link/anchor), or
selection.anchorNode.parentElement.nodeName.toLowerCase() == 'a') // Node parent is of type 'a' (link/anchor)
// Do not convert, or show actions if selection is a link (usually when user has right clicked on a link)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment