How to select text in IE? - javascript

I'm using the following function to get selected text and it works very well in all major browsers but it doesn't work correctly in IE before version 9!
function getSelected() {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
t = t.toString();
} else if (document.selection) {
t = document.selection.createRange();
t = t.text;
}
return t;
}
var txt = getSelected();
The problem here that with IE before version 9 it doesn't store any text in the variable "txt"

DEMO: http://jsfiddle.net/ytJ35/
The below is taken from How to get selected html text with javascript?
this javascript function works in IE7 and above:
function getSelected() {
var text = "";
if (window.getSelection
&& window.getSelection().toString()
&& $(window.getSelection()).attr('type') != "Caret") {
text = window.getSelection();
return text;
}
else if (document.getSelection
&& document.getSelection().toString()
&& $(document.getSelection()).attr('type') != "Caret") {
text = document.getSelection();
return text;
}
else {
var selection = document.selection && document.selection.createRange();
if (!(typeof selection === "undefined")
&& selection.text
&& selection.text.toString()) {
text = selection.text;
return text;
}
}
return false;
}
Tested in chrome, IE10, IE6, IE7

Related

JavaScript / jQuery: get selection function not working in Firefox and Chrome

I am using the following function to get the selected text (i.e. text selected by the user) in a contenteditable div.
This works perfect in IE 9 but not in IE 8, Firefox or Chrome (both latest versions).
Can someone here help me to modify this in a way that it works at least in Firefox and IE 8 as well (Chrome is not a must) ?
My function (working):
function GetSelection()
{
selTxt = '';
if (typeof window.getSelection != "undefined")
{
var sel = window.getSelection();
if (sel.rangeCount)
{
var container = document.createElement('div');
for (var i = 0, len = sel.rangeCount; i < len; ++i)
{
container.appendChild(sel.getRangeAt(i).cloneContents());
}
selTxt = container.innerHTML;
}
}
else if (typeof document.selection != 'undefined')
{
if (document.selection.type == 'Text')
{
selTxt = document.selection.createRange().htmlText;
}
}
return selTxt;
}
Many thanks for any help with this, Tim.
function myGetSelection(){
if(document.selection){ //IE
return document.selection.createRange().text;
} else{
return window.getSelection().toString();
}
}

getSelection returning text after cleared

JS Fiddle
JS
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
console.log(html); <-- returning text even not selected.
}
$(document).ready(function(){
$(document).bind("mouseup", getSelectionHtml);
});
I'm currently trying to understand the following behavior:
1) Select a few lines of text (console.log shows those lines) - expected.
2) Click within the selection you've made. Console.log then shows the same text as the previous, which was selected. - Not expected; here I expect getSelection to return nothing as nothing is currently selected.
Can anyone tell me what i'm missing here?
Thanks!
DEMO jsFiddle
JS
var previousText = '';
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
if(html!= previousText) {
console.log(html);
}
previousText = html;
}
$(document).mousedown(function () {}).mouseup( function () {
getSelectionHtml();
});
To not show empty selections just change:
if(html!= previousText) {
to this:
if(html!= previousText && html != '') {
Note: I'm using jQuery because you were too

how to get HTML with "window.getSelection()"

My code:
<p id="p">
123<span>abc</span>456
</p>
<script>
document.getElementById("p").onmouseup=function(){
if (window.getSelection) {
//code
}
else if (document.selection) {
alert(document.selection.createRange().htmlText) //IE6 7 8
}
}
</script>
what to write at "//code" that I could get the same htmlText in chrome or FF ?
http://jsfiddle.net/kyP83/
document.getElementsByTagName('p')[0].onmouseup = function() {
if (typeof window.getSelection === 'function') {
//code
var selObj = window.getSelection();
alert(selObj);
var selRange = selObj.getRangeAt(0);
} else if (document.selection) {
alert(document.selection.createRange().htmlText) //IE6 7 8
}
}

Get parent element of a selected text

Is it possible to get the parent element of a selected text in the page? For example:
<div class="someparent">
Selection of this text should refer to the 'someparent' class.
<span class="spanparent">If this is selected, the parent should be this span</span>
</div>
Because when getting the selected text, it normally gets it from the window or the document (depending on the browser) but is it that possible to get the parent element of the selected text?
Here's a function that will get you the innermost element that contains the whole of the user selection in all major browsers (except when multiple ranges are selected, which is only supported in Firefox. If this is important, I can expand the example to deal with that case too):
function getSelectionParentElement() {
var parentEl = null, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
parentEl = sel.getRangeAt(0).commonAncestorContainer;
if (parentEl.nodeType != 1) {
parentEl = parentEl.parentNode;
}
}
} else if ( (sel = document.selection) && sel.type != "Control") {
parentEl = sel.createRange().parentElement();
}
return parentEl;
}
I'd suggest to use this
window.getSelection().anchorNode.parentElement
I have tested in safari osx 10.9
#Tim Down's answer works good, to add more useful code for reaching the specific parent's html content:
function getSelectionParentElement() {
var parentEl = null, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
parentEl = sel.getRangeAt(0).commonAncestorContainer;
if (parentEl.nodeType != 1) {
parentEl = parentEl.parentNode;
}
}
} else if ( (sel = document.selection) && sel.type != "Control") {
parentEl = sel.createRange().parentElement();
}
while(true){
// I want to reach upper <span> parent
if(parentEl.nodeName == "SPAN"){
console.log(parentEl);
break;
}
else{
parentEl = parentEl.parentNode;
}
}
}
For example:
function getSelectionParentElement() {
var parentEl = null, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
parentEl = sel.getRangeAt(0).commonAncestorContainer;
if (parentEl.nodeType != 1) {
parentEl = parentEl.parentNode;
}
}
} else if ( (sel = document.selection) && sel.type != "Control") {
parentEl = sel.createRange().parentElement();
}
while(true){
// I want to reach upper <span> parent
if(parentEl.nodeName == "P"){
document.getElementById("printable").innerText = parentEl.innerHTML;
break;
}
else{
parentEl = parentEl.parentNode;
}
}
}
<head>
<style type="text/css">
#media print
{
#non-printable { display: none; }
#printable { display: block; }
}
</style>
</head>
<p>The <strong>coronavirus</strong> COVID-19 is affecting <strong>210 <i>countries</i> and territories</strong> around the world and 2 international conveyances.</p>
<div id="printable">Output: </div>
<button onclick="getSelectionParentElement()">Select 'countries' and click me.</button>

Find space at cursor in TEXTAREA

Is there anyway to check if the character at the cursor in TEXTAREA is a "space"? If it is, return TRUE. Let me know how to do this using jQuery.
Thanks
This works in recent versions of the main browsers and has the added bonus of not requiring jQuery or any other library:
function nextCharIsSpace(textArea) {
var selectedRange, range, selectionEndIndex;
// Non-IE browsers
if (typeof textArea.selectionEnd == "number") {
selectionEndIndex = textArea.selectionEnd;
}
// IE is more complicated
else if (document.selection && document.selection.createRange) {
textArea.focus();
selectedRange = document.selection.createRange();
range = selectedRange.duplicate();
range.moveToElementText(textArea);
range.setEndPoint("EndToEnd", selectedRange);
selectionEndIndex = range.text.length;
}
return textArea.value.charAt(selectionEndIndex) === " ";
}

Categories