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:

constisLink = () => {
  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 { returnfalse }
    } else { returnfalse }
  }
}

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 selectedwindow.getSelection().containsNode(linkHtmlElement)

Post a Comment for "Check If Selection Contains Link"