How to get Selected Text from DIV - javascript

I'm getting the selected text from textarea but I can't get it from a div.
I'm trying with document.getElementById('myDiv') but it doesn't work.
To be more specific. When I have text, using this method I can get the selected text
function TestSelection ()
{
if (window.getSelection) {
var selectionRange = window.getSelection();
alert ("The text content of the selection:\n" + selectionRange.toString());
}
}
but I cant specify the div to get it's selected text. Only from this div, not from another.
I tried var value = document.getElementById("myDiv").innerHTML;
and then value.getSelection but it doesn't work too.
Thank you very much!!!

Simply ,do the following :
var ss=getSelection();
ss.baseNode.data.substring(ss.baseOffset,ss.extentOffset);

Use the innerHTML property
var html = document.getElementById('myDiv').innerHTML;

You should use innerHTML property:
var value = document.getElementById("myDiv").innerHTML;

You should use Selection
var selObj = window.getSelection();
window.alert(selObj);

for jquery
var str = $("#myDiv").text();
str is the text

Related

get content of element after slicing his span

I have the next element:
<div id = "mydiv">
abc
<span>123</span>
</div>
document.getElementById('mydiv').textContent returns me: abc123
I want to get only the text of mydiv ('abc'). so I wonder if there is an option to use jquery in order to get it? maybe get all the content of an element except for span element..
and then getting his text..
p.s. I know I can wrap abc in span and then get it, but I wonder if there is another option to do it without changing my element..
DEMO JSFIDDLE
Try this ,
console.log($("#mydiv").clone() .children().remove().end().text());
You must select yours DIV by ID, then run through its "childrens" property and check their nodeType (textNodes has 3);
var div = document.getElementById("mydiv");
var result = "";
for(var i = 0; i < div.length; i++){
var node = div[i];
if( node.nodeType === 3 ){
result += node.data;
}
}
console.log(result);
Since you've included jQuery you can do this
var p = $('#mydiv').clone();
p.find('span').remove();
console.log(p.text());
DEMO
Using jQuery:
$(document).ready(function() {
alert($('#mydiv span').text());
});
If you expect to have more html elements inside your div, user regular expression to extract plain text after getting whole html content from div.
var re = /<.+>/;
var str = "abc<span>123</span>";
var newstr = str.replace(re, "");
Should give "abc"

How can I toggle a class on selected text?

I'm trying to create a fairly simple text editor (bold, italic, indent) and need to be able to toggle the class associated with the button on click. I have this code:
var selected = function ()
{
var text = '';
if (window.getSelection) {
text = window.getSelection();
}
return text;
}
$('textarea').select(function(eventObject)
{
console.log(selected().toString());
var selectedtext = selected().toString();
$('#bold-button').click(function () {
$(selectedtext).addClass('bold-text');
});
});
And I can get the selected text to print, but can't get the class added. I've seen other solutions that add the class on click to the entire textarea, but I dont need that. Any help?
You could use surroundContents() like below. Before demo here http://jsfiddle.net/jwRG8/3/
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);
}
}
}
But this is not supported less than IE9. And I worked on text selections before and I found them in consistent. Tim Down is very much experienced on selections and most of the answers in SO related to Selections are given my him. He has written a plugin called rangy. You mat try it at https://code.google.com/p/rangy/
Because you are selecting text directly, there is no element to add the class on. textNodes cannot have classes. Instead, try wrapping the text in an element:
$('textarea').select(function(eventObject) {
console.log(selected().toString());
var selectedtext = selected().toString();
$(selectedtext).wrap('<span />').parent().addClass('bold-text');
})
Or you could just wrap it in a b tag, without the class:
$(selectedtext).wrap('<b/>');

Getting already selected text

By using following code I am getting the selected text's startindex and the selected text itself. I am storing them in a local database. I am changing the selected text background color to yellow.
var mainDiv = document.getElementsByTagName("body")[0];
var sel = getSelectionCharOffsetsWithin(mainDiv);
var selectedText = window.getSelection();
location.href = selectedText + '*' + sel.start; // this is to call iOS function.
var range = window.getSelection().getRangeAt(0);
var span = document.createElement("span");
span.style.backgroundColor = "yellow";
span.setAttribute("id", sel.start);
range.surroundContents(span);
Now, I am doing something else, and again I come back to same page. Here now I want to show previously selected text as highlighted.
Use Rangy , nothing beats it , does exactly what your trying
Rangy
Have a look at this demo

Obtain selected text from IFRAME using Rangy

I am trying to get selected text of Iframe using Rangy using this function;
function getSelectedText() {
var iframe = document.getElementById("CustomeHTMLViewer");
var iframeWin = iframe.contentDocument ? iframe.contentDocument.defaultView : iframe.contentWindow;
var sel = rangy.getSelection(iframeWin);
return sel;
}
This code is not working; how can I get selected text of an Iframe?
Rangy has a convenience method for this: rangy.getIframeSelection(). Example:
var iframe = document.getElementById("CustomeHTMLViewer");
var sel = rangy.getIframeSelection(iframe);
To get hold of the selected text, call toString() on the selection:
var selectedText = sel.toString();
alert(selectedText);
Rangy allows an iframe element to be passed directly into rangy.getSelection().
Having said all that, there doesn't actually seem to be anything wrong with your original code.

how to select a text range in CKEDITOR programatically?

Problem:
I have a CKEditor instance in my javascript:
var editor = CKEDITOR.instances["id_corpo"];
and I need to insert some text programatically, and select some text range afterwards.
I already did insert text through
editor.insertHtml('<h1 id="myheader">This is a foobar header</h1>');
But I need to select (highlight) the word "foobar", programatically through javascript, so that I can use selenium to work out some functional tests with my CKEditor plugins.
UPDATE 1:
I've also tried something like
var selection = editor.getSelection();
var childs = editor.document.getElementsByTag("p");
selection.selectElement(childs);
But doesn't work at all!
How can I do that?
I think that
selection.selectRange()
could do the job, but I'could not figure out how to use it.
There are no examples over there :(
Get current selection
var editor = CKEDITOR.instances["id_corpo"];
var sel = editor.getSelection();
Change the selection to the current element
var element = sel.getStartElement();
sel.selectElement(element);
Move the range to the text you would like to select
var findString = 'foobar';
var ranges = editor.getSelection().getRanges();
var startIndex = element.getHtml().indexOf(findString);
if (startIndex != -1) {
ranges[0].setStart(element.getFirst(), startIndex);
ranges[0].setEnd(element.getFirst(), startIndex + findString.length);
sel.selectRanges([ranges[0]]);
}
You can also do the following:
get the current selection
var selection = editor.getSelection();
var selectedElement = selection.getSelectedElement();
if nothing is selected then create a new paragraph element
if (!selectedElement)
selectedElement = new CKEDITOR.dom.element('p');
Insert your content into the element
selectedElement.setHtml(someHtml);
If needed, insert your element into the DOM (it will be inserted into the current position)
editor.insertElement(selectedElement);
and then just select it
selection.selectElement(selectedElement);
Check out the selectElement() method of CKEDITOR.dom.selection.
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.dom.selection.html
insert text at cursor point in ck editor
function insertVar(myValue) {
CKEDITOR.instances['editor1'].fire( 'insertText',myValue);
}
this is working for me

Categories

Resources