Rangy: How can I get the span element created with the Highlighter module?

I'm using the highlighter module available in Rangy and it works great in making a selection for the selected text.

As for the html changes, the selected text is replaced with a span tag, like the following:

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 after it's created so I can do other things with it. How can I do that?

Note that there may be other scrolls elsewhere with or without a label, so cannot be found to find it.

The important part of the code that I have to create a selection 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);

      

+3


source to share


2 answers


I was waiting for @TimDown to update his answer with working code. But since he didn't, I'll post someone (which is based on his answer).

The following function will return an array of highlight items that were created, 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;
}

      

+4


source


There is no guarantee that only one element will be created <span>

: if the selection crosses the boundaries of the elements, you can create multiple gaps.

Anyway, since the selection is saved, you can use getNodes()

the selection range method to get the gaps:



var spans = selection.getRangeAt(0).getNodes([1], function(el) {
    return el.tagName == "SPAN" && el.className == "highlight";
});

      

+4


source







All Articles