dom-highlight-range
dom-highlight-range copied to clipboard
Customize the element used for highlighting
In my application, I need to track additional information about each logical highlight. Today, it’s only possible to specify a class attribute for a span that’s created automatically. This is convenient, but not flexible enough. I’d like to be able to customize how the library constructs highlight wrappers to be able to add additional context to each highlight wrapper node. For example,
function renderAnnotation(annotation, range) {
highlightRange(range, function() {
var span = document.createElement('span');
span.classList.add('annotation');
span.dataset.annotationId = annotation.id;
return span;
});
}
This example adds a unique identifier for each logical highlight via a closure.
~PR forthcoming.~ #2
This is a valid desire indeed, thanks for picking it up! I have had a similar intention to give this module more flexibility some day.
I would actually have no problem with making breaking changes to the API, then releasing it as v2.0. So feel free to suggest whatever arguments, return value and defaults seem most sensible. For example, I was thinking to make it wrap text in a <mark> element by default, rather than a <span> with the hard-coded class 'highlighted-range'. Then changing the class and/or element type could be done in the way you suggest; perhaps as a shorthand one could alternatively pass a name and attributes, e.g. highlightRange(range, 'span', {class: 'my-highlight'}). Just thinking out loud here.
I need to add some tests, but I think #2 adds this capability without changing the existing signature. If you pass it a string, it will still create a span with that class name, just as before. My changes sniff out passing a pre-fab HTMLElement or a factory function that will build the wrapper element. I’d expect these to be completely backward compatible with 1.0.
I’ll clean up my PR and add some tests (err, probably some manual HTML that exercises the three options) and re-submit, hopefully this weekend.
Thanks for your consideration. This library did exactly what I needed. Cheers.
Sure. I am happy to first make a v1.1 that is backwards compatible, then leave the other API ideas for later. Tests would be most welcome anyhow.