39

I'm extending a WYSIWYG HTML editor (for Firefox), I want to add tags around a selection. I can't find a function to accomplish this in the Mozilla Midas specification.

There is a command to replace the selection with HTML.
So if I could read the selection contents, I could add my tags to this string.

window.getSelection() almost works, but it gives me nsISelection which converts to a plain-text string.

PS: document.getSelection() returns the plain-text string not even a nsISelection.

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
Bob Fanger
  • 28,949
  • 7
  • 62
  • 78
  • Hey Bob Fanger did u find any solution for this.If u have can u just tell me. – Warrior Nov 11 '10 at 10:46
  • Nope, we switched to TinyMCE, which solved the (business) problem. PS. TinyMCE has a great api for extending their htmleditor. You could check the implementation of http://wiki.moxiecode.com/index.php/TinyMCE:API/tinymce.Editor/selection – Bob Fanger Nov 13 '10 at 22:11
  • I suggest that you take a look at some (well-developed) WYSIWYG htmleditor - tinymce, for example - to figure it out. :) – Limbo Peng Jan 26 '10 at 14:12

4 Answers4

49

Take a look at the DOM Range spec. You can get a Range from the user selection in Firefox using:

var range = window.getSelection().getRangeAt(0);

Note that some browsers, including Firefox, allow multiple selections, which can be accessed via the getRangeAt() method of the selection.

The Range is expressed in terms of DOM nodes and offsets within those nodes. Once you've got your Range, it's not straightforward to do exactly what you want, since the range's boundaries could be in different nodes at different levels of the DOM tree, so simply surrounding the Range's content with a tag is not always possible. You may be able to do something like the following, although it will create a new block element to contain the selected content:

var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var div = document.createElement("div");
div.style.color = "yellow";
div.appendChild(selectionContents);
range.insertNode(div);

Another, hacky, alternative is to use the execCommand() method of document to modify the selection (e.g. by setting it to a particular colour) and then using document.querySelectorAll or some selector library to select elements with that colour and then apply styling to them.

Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • there's a minor typo on the last line, you need to s/span/div/ – Will Moffat Sep 30 '10 at 19:07
  • @tim problem is that if I will try to extract start and end from range object this is not returning exact position which is giving me through **window.getSelection()** object.. any way to get and if I use both then **window.getSelection().getRangeAt(0)** range start and end overrides the **window.getSelection()** object start and end value. any way for more please follow this link I have posted here http://stackoverflow.com/questions/42113694/how-to-get-selected-text-range-and-add-color-to-the-particular-selected-text/42114215#42114215 – Tamaghna Banerjee Feb 08 '17 at 16:47
  • This made my day :) Thanks @TimDown – Lazyexpert Jun 16 '17 at 07:39
18

Tim Down's answer is on the right track. However one issue is that extractContents() will remove the selection from the dom. You can use

window.getSelection().getRangeAt(0).cloneContents(); 

to just get a copy of what's selected. You could then wrap that with your new tag and then replace the selection with it. Tim Down's concern about the range spanning multiple HTML elements is certainly a valid one. I think once you get the range, it 'fixes' up the html, but when you put it back in it could cause problems. Here's a good resource on the Range object.

rosscj2533
  • 9,195
  • 7
  • 39
  • 56
  • 2
    I hadn't quite finished when I posted. I've now completed my answer. Using `extractContents` was deliberate since you need to remove the content from the document before reinserting it. – Tim Down Jan 26 '10 at 15:31
  • Yeah, I figured there would be a pretty nice way to use extractContents to solve this, I just thought I should point out that it's 'destructive' and there's another method to get the selected html. Anyway, good answer, +1. – rosscj2533 Jan 26 '10 at 15:49
8

window.getSelection() will return an object. You can use the returned selection object as a string by calling the objects .toString() method.

var selObj = window.getSelection();
var selectedText = selObj.toString(); 

https://developer.mozilla.org/en/DOM/window.getSelection

Dave Roma
  • 2,449
  • 3
  • 18
  • 13
0
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>select content of particular element</title>
</head>

<body>
    <div id="div">This is the div tag</div>
    <p>this is the paragraph</p>
    <button id="Btn">Button</button>
    <script>
        let Btn = document.getElementById("Btn");
        Btn.addEventListener("click", function () {
            let selection = document.getSelection();
            if (selection.anchorNode.parentElement.id == "div") {
                let selectionContents = document.getSelection().toString();
                console.log("selected content of div id :", selectionContents)
            }
            else{
                console.log("pls select some text")
            }
        })
    </script>
</body>

</html>