rangy icon indicating copy to clipboard operation
rangy copied to clipboard

Handle more than one class in ClassApplier::addClass Method

Open AdamMcCormick opened this issue 9 years ago • 4 comments

I'm attempting to use rangy to apply highlights and notes to a document reader application. While the library is really good at applying the highlights, I need to add several different classes to each highlight. I can't seem to find any means of doing that with the ClassApplier as-is. This change allows the caller to pass a space-separated list of classes to a ClassApplier and thereby add as many classes as needed.

My apologies if this isn't the right process to make such a suggestion.

AdamMcCormick avatar Jun 22 '15 20:06 AdamMcCormick

+1 for this feature request.

Rangy used to support this in 1.3alpha.722 because it appended to an element's className property, whereas now classList is used.

// old 1.3alpha.722 function
function addClass(el, cssClass) {
    if (el.className) {
        if (!hasClass(el, cssClass)) {
            el.className += " " + cssClass;
        }
    } else {
        el.className = cssClass;
    }
}

nicholascloud avatar Jul 20 '15 20:07 nicholascloud

I am also in need of this functionality, would be awesome is this is merged in.

geirsagberg avatar Sep 09 '15 11:09 geirsagberg

I am using this workaround:

    rangy.createClassApplier('snippet', {
      elementTagName: 'span',
      onElementCreate: el => {
        el.className = cx(el.className, 'another-class');
      },
    });

LeZuse avatar Dec 02 '15 18:12 LeZuse

A documented solution for adding an extra class is to use the className property in the elementAttributes object.

rangy.createClassApplier('firstClass', {
    elementAttributes: {
        className: 'secondClass'
    }
});

But I wasn't able to get this method to work for more than one extra class since the className property doesn't accept any tokens with whitespace. If anyone knows better let me know. For now, @LeZuse's solution still works.

MimmyJau avatar Feb 21 '23 16:02 MimmyJau