1

Is it possible to change the stlye of the text in a selection?

<p onmouseup="mouseUp()">This is a text for testing the selection</p>
<script>
function mouseUp() {
    var selection = window.getSelection();
    alert(selection.toString());
    //can I cahnge the color of e.g. the first character of the selection?
}
</script>
nagy.zsolt.hun
  • 6,292
  • 12
  • 56
  • 95
  • You can access selection.extentNode.parentNode to replace selection (using jQuery append() function) with a span with proper formatting but it'll be much more complicate because a selection can span across multiple nodes (and this is just first problem you may have). It's easy to do only for a very simple scenario – Adriano Repetti Mar 08 '14 at 10:39

3 Answers3

2

I've already had this problem, and found the following explanation and implementation useful:

http://jsfiddle.net/VRcvn/

function surroundSelection(element) {
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(element);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
}

(taken from: Wrapping a selected text node with span)

EDIT: to also change the style, here is a simple example

<p onmouseup="surroundSelection()">This is a text for testing the selection</p>
<script>

function surroundSelection() {
    var span = document.createElement("span");
    span.style.fontWeight = "bold";
    span.style.color = "green";

    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(span);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
}
Community
  • 1
  • 1
Shay Elkayam
  • 4,128
  • 1
  • 22
  • 19
0

You would need to wrap the first character in an element (span for example) and then apply some css or a class to that element.

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
  • This is how you wrap it: Put your code here – les Mar 08 '14 at 10:38
  • The code in my question provides a string (the selected text). Obviously I can create a new span element with this string; but my question is how to set the style of the actually selected text? (in the p element in my example). – nagy.zsolt.hun Mar 08 '14 at 10:41
0

Try this - it works: click on the "T" and it will change to blue

<p onclick="mouseUp()">
    <span id="first_Letter">T</span>his is a text for testing the selection
</p>
<script>
    function mouseUp() {
        var first_L = document.getElementById("first_Letter");
        first_L.style.color = "blue";
    }
</script>
les
  • 564
  • 7
  • 19