Check if selection contains link

2019-08-28 16:54发布

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条回答
\"骚年 ilove
2楼-- · 2019-08-28 17:48

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 }
  }
}
查看更多
登录 后发表回答