Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rangy: How can I get the span element that is created using the Highlighter module?

I am using the highlighter module available in Rangy, and it work great in creating a highlight for the text that is selected.

In terms of changes to the html, the selected text is replaced by a span tag like the following for example:

the selected text is <span class="highlight">replaced by a span tag</span> like the

What I want to do is get a reference to the span element once it has been created so I can do some other stuff with it. How can this be done?

Please note there may be other spans with or without the highlight tag elsewhere, so these cannot be used to find it.

The important part of the code I have to create the highlight for the selected text is:

var highlighter = null;
var cssApplier = null;

rangy.init();
cssApplier = rangy.createCssClassApplier("highlight", { normalize: true });
highlighter = rangy.createHighlighter(document, "TextRange");
highlighter.addClassApplier(cssApplier);

var selection = rangy.getSelection();
highlighter.highlightSelection("highlight", selection);
like image 268
musefan Avatar asked Jan 15 '23 07:01

musefan


2 Answers

I was waiting for @TimDown to update his answer with working code. But as he hasn't done that then I will post some myself (which is based on his answer).

The following function will return an array of highlight elements that have been creating, assuming the selection is still valid:

function GetAllCreatedElements(selection) {
    var nodes = selection.getRangeAt(0).getNodes(false, function (el) {
        return el.parentNode && el.parentNode.className == "highlight";
    });

    var spans = [];

    for (var i = 0; i < nodes.length; i++) {
        spans.push(nodes[i].parentNode);
    }
    return spans;
}
like image 113
musefan Avatar answered Jan 16 '23 22:01

musefan


There is no guarantee that only one <span> element will be created: if the selection crosses element boundaries, several spans could be created.

Anyway, since the selection is preserved, you could use the getNodes() method of the selection range to get the spans:

var spans = selection.getRangeAt(0).getNodes([1], function(el) {
    return el.tagName == "SPAN" && el.className == "highlight";
});
like image 38
Tim Down Avatar answered Jan 16 '23 20:01

Tim Down