Skip to content Skip to sidebar Skip to footer

Check If Selection Contains Link

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'...)

Solution 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 }
  }
}

Solution 2:

You also may be able to retrieve the link HTML element and pass it to Selection.containsNode()

const linkHtmlElement = document.getElementById('yourId');
// should return true if your linkHtmlElement is selected
window.getSelection().containsNode(linkHtmlElement)


Post a Comment for "Check If Selection Contains Link"