0

I'm working on an rich text editor that can be embedded in a web page along the lines of Aloha. The current problem I'm running up against is when inserting or updating links around a user-created selection of text I need to know whether a link already exists around that selection or not so that I can either update or insert, respectively.

For example, suppose the square brackets ([ and ]) represent the bounds of the selected range:

Case 1:

this is [some unlinked text]

Case 2:

this is <a href='stackoverflow.com'>some [linked] text</a>

Case 3:

this is <a href='stackoverflow.com'>[some linked text]</a>

In case 1 and 2 I want to know that there is NOT an element immediately enveloping the selected text and in case 3 I want to get that ANCHOR tag that is immediately surrounding the selected text. I'm wondering what an efficient, cross-browser solution might look like.

Also, I know that the Range object has a commonAncestorContainer property but sometimes that property references a text node rather than an element node.

Patrick Canfield
  • 1,655
  • 1
  • 13
  • 17

1 Answers1

0

Using jQuery:

getWrappingElement = function(range) {
  var $wrapper;

  $wrapper = $(range.commonAncestorContainer);

  // handle cases in which range.commonAncestorContainer is a text node
  if ($wrapper.parent().text().trim() === range.toString().trim()) {
    $wrapper = $wrapper.parent();
  }

  if ($wrapper.get(0).nodeType === document.ELEMENT_NODE) {
    return $wrapper;
  } else {
    return false;
  }
}

Where range is a Range object.

Patrick Canfield
  • 1,655
  • 1
  • 13
  • 17