Search code examples
javascriptrangy

Rangy: how do I expand the selection based on parent node?


html that is being selected:

some te<b>xt here is bold</b>ed, I guess
              |______________________|  <- the selection range

so, the selected .toHtml() is this:

<b>ere is bold</b>ed, I gue

but this is not in the original document.

So, what I want to do is expand the selection so that it contains the entire BOLD tag.

This is easy to detect, as you just need to do a test if

a = rangy.getSelection()
a.anchorNode.parentElement != a.focusNode.parentElement

The documentation states that rangy ranges have a setStartBefore(Node) method : http://code.google.com/p/rangy/wiki/RangyRange

so, I get the current range

b = a.getRangeAt(0)

and try to setStartBefore :

b.setStartBefore(a.anchorNode.parentNode)

and since I'm doing this all in the console, I get the immediate feedback saying

undefined

what would be causing this, and how I would go around it to find a solution for the problem I want to solve?

UPDATE: as per Tim Down's suggestion, I've tried the following:
enter image description here Original Text:
enter image description here

It should have expanded to include Mass Ef shouldn't it have?

UPDATE 2:

The solution (as per Tim Down) enter image description here


Solution

  • You need to reselect the range:

    a.setSingleRange(b);
    

    By the way parentElement is not universally supported: it started out IE only, has relatively recently made it into the DOM4 spec and is not yet supported in Firefox (support is coming in Firefox 9.0, apparently). You'll need a workaround based on parentNode and nodeType.