Check if selection contains link

2019-08-28 17:48发布

问题:

I am creating a rich text editor and I would like to use the same button to link and unlink selections.

document.execCommand('createLink'...) and document.execCommand('unlink'...) allow users to link and unlink window.getSelection().toString().

However, there are no inbuilt methods to determine whether a selection is linked or not in the first place, so my question is: How can you check whether or not a selection is linked?

I have tried using document.queryCommandState('createLink') and document.queryCommandState('unlink'), but both queries always return false, even though, for example, document.queryCommandState('bold') works properly.

回答1:

I found the following piece of code, which works well enough for the time being, kicking around on SO:

const isLink = () => {
  if (window.getSelection().toString !== '') {
    const selection = window.getSelection().getRangeAt(0)
    if (selection) {
      if (selection.startContainer.parentNode.tagName === 'A'
      || selection.endContainer.parentNode.tagName === 'A') {
        return [true, selection]
      } else { return false }
    } else { return false }
  }
}