maestro
maestro

Reputation: 11

How to replace selected text on page with another text?

I'm trying to replace selected text with another text with a function switchText called from the context menu.

function switchText(info) {

var text = info.selectionText;     // selected text

// then I do some manipulations with 'text' and get 'text_to_replace'

var text_to_replace = "some text"; // text to replace

}

alert(text) and alert(text_to_replace) works fine, but I'm trying to replace selected text right on the page but I can't figure out how to do it. I tried different methods but they hadn't worked. Any special permissions needed? I'm sorry if it's stupid question, I'm beginner in JS.

Upvotes: 1

Views: 784

Answers (2)

Brian
Brian

Reputation: 4344

If you want to be able to do this anywhere on a page, you need to be able to set some kind of identifying ID to your selection. You have to do this through a content script of some kind. You can read more about it in the Chrome Developer documentation.

This code will allow you to change the text of a single selection

(tested in Chrome only)

function switchText(id) {
    // Gets the selection range
    // This is from Tim Down, linked below
    var range, sel = window.getSelection();
    if (sel.rangeCount && sel.getRangeAt) {
        range = sel.getRangeAt(0);
    }
    // Creates a new node range
    document.designMode = "on";
    if (range) {
        sel.removeAllRanges();
        sel.addRange(range);
    }
    // This is from user YeppThatsMe, also linked below
    document.execCommand("insertHTML", false, "<span id='own-id'>"+ document.getSelection()+"</span>");

    document.designMode = "off";

    // You can use either a variable or a string
    var someNewText = "-- You can make this whatever you want --";

    // Finds the new span and replaces the selection with your new text
    document.getElementById("own-id").innerHTML=someNewText;
};

Sourced scripts

Tim's script

HTML5 inserCommand

Last Note

I didn't spend too long testing, and the script as-is will only change one selection per page. You'll need to tweak the way the function gets the tag and attribute info (change it to getElementsByClassName?) to run it more than once, but this should work.

Upvotes: 1

rob
rob

Reputation: 8410

to update a html element targeted by Id

document.getElementById("idtotarget").innerHTML = switchText(document.getElementById("idtotarget").innerHTML)

Upvotes: 0

Related Questions