title: Rangy range contained within a jquery selector
body: <p>I'm working on a JavaScript wrapper around the <a href="http://code.google.com/p/rangy/" rel="nofollow">Rangy JavaScript plugin</a>. What I'm trying to do: given a jQuery selector and a range, detect if the range is contained within the selector. This is for a space where a user will read a document and be able to make comments about particular sections. So I have a div with <code>id="viewer"</code> that contains the document, and I have an area of buttons that do things after a user selects some text. Here is the (broken) function:</p>
  
  <pre><code>function selectedRangeInRegion(selector) {
      var selectionArea = $(selector);
      var range = rangy.getSelection().getRangeAt(0);
      var inArea = (selectionArea.has(range.startContainer).length &gt; 0);
  
      if (inArea) {
          return range;
      } else {
          return null;
      }
  }
  </code></pre>
  
  <p>It appears that <code>selectionArea.has(range.startContainer)</code> returns an array of size 0. I have tried wrapping like: <code>$(range.startContainer)</code>. Any tips?</p>
  
  <hr>
  
  <p>I developed a solution for this problem. This assumes you have a div selector and that your content does not have any divs:</p>
  
  <pre><code>function containsLegalRange(selector, range) {
    var foundContainingNode = false;
  
    var container = range.commonAncestorContainer
  
    var nearestDiv = $(container).closest("div");    
    if (nearestDiv.attr("id") == selector) {
      return true
    }
    else {
      return false
    }
  }
  </code></pre>