Search code examples
javascriptrangy

How can I create tags using Rangy.js without a class attribute?


I've been playing with Rangy.js for selection ranges and so far really like it. I'm looking to wrap a selection range's text nodes within a certain tag and toggle this upon button click. I have it working great using the cssClassApplierModule with the exception of (and it makes sense due to the name) I HAVE to also give the dom element a class that it's applying to itself.

So right now when I select a range and apply for instance a strong tag, my end result is:

Text text text <strong class="test"> selected text </strong> text text text

And I'd like it to be:

Text text text <strong> selected text </strong> text text text

The code I have so far is as follows:

function gEBI(id) {
                return document.getElementById(id);
            }

            var action;

            function toggleAction() {
                action.toggleSelection();
            }

            rangy.init();

            // Enable buttons
            var cssClassApplierModule = rangy.modules.CssClassApplier;

            // Next line is pure paranoia: it will only return false if the browser has no support for ranges,
            // selections or TextRanges. Even IE 5 would pass this test.
            if (rangy.supported && cssClassApplierModule && cssClassApplierModule.supported) {
                action = rangy.createCssClassApplier("test", {
                    elementTagName: "strong",
                    elementProperties: { }
                });
                var toggleActionButton = gEBI(nsID);
                toggleActionButton.disabled = false;
                toggleActionButton.ontouchstart = toggleActionButton.onmousedown = function () {
                    toggleAction();
                    return false;
                };
            }

I tried "" and null instead of "text" as the css class being passed, and it will toggle, but no longer toggle off and is obviously not the correct solution.

Any help appreciated.. Thanks!


Solution

  • Rangy's CSS class applier won't let you do this, unfortunately. The fundamental problem is that it relies on the CSS class to decide which elements and text nodes to surround or add/remove classes from. It's considerably simpler to detect the presence of a class than the more general case of detecting a style, such as boldness.

    I did some work last year on a more ambitious and generic execCommand module that would do what you want. It got as far as a working demo but I got bogged down in tricky edge cases and stopped working on it. I do intend to go back to it but it's likely to be months before anything is ready.