Is it possible to get the highlighted text in a paragraph of a website e.g. by using jQuery?
Getting the text the user has selected is relatively simple. There's no benefit to be gained by involving jQuery since you need nothing other than the window
and document
objects.
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
If you're interested in an implementation that will also deal with selections in <textarea>
and texty <input>
elements, you could use the following. Since it's now 2016 I'm omitting the code required for IE <= 8 support but I've posted stuff for that in many places on SO.
function getSelectionText() {
var text = "";
var activeEl = document.activeElement;
var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
if (
(activeElTagName == "textarea") || (activeElTagName == "input" &&
/^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&
(typeof activeEl.selectionStart == "number")
) {
text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
} else if (window.getSelection) {
text = window.getSelection().toString();
}
return text;
}
document.onmouseup = document.onkeyup = document.onselectionchange = function() {
document.getElementById("sel").value = getSelectionText();
};
Selection:
<br>
<textarea id="sel" rows="3" cols="50"></textarea>
<p>Please select some text.</p>
<input value="Some text in a text input">
<br>
<input type="search" value="Some text in a search input">
<br>
<input type="tel" value="4872349749823">
<br>
<textarea>Some text in a textarea</textarea>
window.getSelection()
). The document.selection.type
check is testing that the selection is a text selection rather than a control selection. In IE, a control selection is a selection inside an editable element containing one or more elements (such as images and form controls) with outlines and resize handles. If you call .createRange()
on such a selection, you get a ControlRange
rather than a TextRange
, and ControlRange
s have no text
property. –
Consciencestricken today is a wonderful day
then user select day is a wonderful d
, it world complete select the whole sentence automaticlly.) Thanks. –
Ranie TextRange
in IE has an expand()
method) and WebKit has a non-standard expand()
method in its DOM Range extension. However, this doesn't cover all browsers. One (somewhat heavyweight) option for a cross-browser solution is the TextRange module of my own Rangy library. –
Consciencestricken document.execCommand()
: #2583331 –
Consciencestricken input
to be included, you can conditionally use a combination of document.activeElement
and the DOM properties selectionStart
, selectionEnd
and value
of that active element to get its selected text. This was useful for me when I needed to disable left/right swipe when ANY text in the page was selected. –
Inoculation textarea
s in Firefox. This is a known bug. –
Novelette .activeElement
and I don't see the point for checking the type of the element as well as of .selectionStart
, which is also supported by practically every browser. Maybe I forget thinking about some edge case, but at least in my extended test case of yours, your code offers no benefit compared to mine; they work exactly the same: jsfiddle.net/6zoposby vs. jsfiddle.net/6zoposby/1 –
Novelette .splice()
instead of .substring
btw? Is it faster? O.o –
Novelette selectionStart
or selectionEnd
in an <input>
element type (such as "number") that doesn't support it (see jsfiddle.net/6zoposby/2, for example). I left the check for the existence of selectionStart
so that the code won't break in IE <= 8. I admit the check for activeElement
is probably overkill now. I use slice
because it's more powerful (though that's not useful here) and slightly shorter to type than substring
. –
Consciencestricken selectionStart
, we already agreed on removing the 2nd branch from your first code anyway, which was also for compatibility with IE below v9.. ;) –
Novelette input
fields? is it not possible to get the content of a div
? –
Geographical div
s. Someone then requested a more general solution that covers cases when the selection is within an input
or textarea
, so I obliged. If you don't need that then you can just use the first version of the function. –
Consciencestricken function getSelectionText(){var W=window,Ds=document.selection; return W.getSelection? W.getSelection().toString(): Ds&&Ds.type!="Control"? Ds.createRange().text:""}
–
Constantan Get highlighted text this way:
window.getSelection().toString()
and of course a special treatment for ie:
document.selection.createRange().htmlText
document.selection
support was removed in IE10 and replaced with window.getSelection
”. Source: connect.microsoft.com/IE/feedback/details/795325/… –
Blackpoll getSelection()
doesn't work on the content of <textarea>
and <input>
elements in Firefox, Edge (Legacy) and Internet Explorer. HTMLInputElement.setSelectionRange()
or the selectionStart and selectionEnd properties could be used to work around this. –
Mischance Use window.getSelection().toString()
.
You can read more on developer.mozilla.org
This solution works if you're using chrome (can't verify other browsers) and if the text is located in the same DOM Element:
window.getSelection().anchorNode.textContent.substring(
window.getSelection().extentOffset,
window.getSelection().anchorOffset)
Yes you can do it with simple JavaScript snippet:
document.addEventListener('mouseup', event => {
if(window.getSelection().toString().length){
let exactText = window.getSelection().toString();
}
}
You can use an event if you want
document.addEventListener('selectionchange', (e)=>{
console.log("Archor node - ",window.getSelection().anchorNode);
console.log("Focus Node - ",window.getSelection().toString());
});
Just find another way to do it. window.getSelection()
is just frustratingly poorly designed. It should have been a text based function, not a node based function from day 1.
Let's take something really basic - you want to highlight a text an make that section bold. Great, window.getSelection() is fantastic for that...once.
However since you also want to make part of that text italic...well...now you're screwed. The text you want to highlight is now divided between 2 or potentially more nodes...which is an issue when the starting point given by window.getSelection() only applies to the specified node and does not take formating into account - the amount of characters to the right of the node that the beginging of the text is in when it's ivided up into several nodes...it just beecomes a fantastic mess.
You can no longer look up the selected phrase in it's entirety as tags like or
will result in you not finding the text, or, if you look up without formatting then you now need to loop through each and every character - and even then you may have several pieces of text that are the same, so looping through the nodes won't help you get where you should do your edits to the text anyways, since you now need to crossrefference formatted and unformatted text...
just don't use it, it's garbage from an era where bad programmers saw it as their duty to dictate what browser you use or how you should highlight text - and if something was buggy or wrong it's the users fault for not doing things the way the programmer wanted them to.
Code something better yourself from scratch instad.
Hell, even something like putting all the letters in an array where each item in the array is a seperate letter and then decide starting point and ending point with onmousedown/onmouseup is simpler an faster instead if you having to deal with window.getSelection()
utter garbage is what it is.
It is woefully unfit for 99% of eeverything you want it to do.
It would have been so much better with `getSelected(text); returning the position of the first and last character as well as the selected text. Or divide it up in 3 seperate functions for all I care.
That woul have been a thousand times better.
© 2022 - 2024 — McMap. All rights reserved.