window.getSelection return html [duplicate] - javascript

This question already has answers here:
HTML of selected text
(2 answers)
Closed 9 years ago.
function selected() {
var selObj = window.getSelection();
}
This function returns selected text from a webpage. How do return the html of a selected area. Is this possible to do with an <img> and an <a> tag?
Here's the list of functions:
https://developer.mozilla.org/Special:Tags?tag=DOM&language=en

The following will do this in all major browsers and is an exact duplicate of this answer:
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;
}
}
return html;
}

Related

jquery getting the html of highlighted text and changing its style

Saw this post about getting the html from the selected/higlighted text. And it does work in getting the html.
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;
}
}
return html;
}
alert(getSelectionHtml());
But, suppose there's this html:
<p>I am <span style="color:green;">green</span> and I have <span style="background-color:yellow;">yellow background<span>.</p>
Now if the word green is highlighted, then it will just get the word
"green"
even if there's <span> tag surrounded. But if selected more character than the word green (say the space before or after the word green like this " green"), it will get the html tag too, such as:
<span style="color:green;">green</span>
Please check out the demo
Is it possible to get the html even if only the word "green" is highlighted?
Eventually what I want to achieve is suppose I want to change the color of the highlighted text to blue color, then first check if the highlighted text has a span. Secondly whether that span has color or background or even both styling. And lastly do the changes to the highlighted text.
$('#change_blue').on("click", function() {
var sel = getSelectionHtml();
/*var span = sel.find("<span").html();*/
alert(sel);
if (sel.match("<span style=")) {
console.log('has span tag');
if (sel.indexOf("background") > -1 && sel.indexOf("color") > -1 ) {
console.log('has both background and color')
// change color to blue
}
else if (sel.match("color")) {
console.log('only color')
// change color to blue
}
else {
console.log('only background')
// add blue color
}
}
else {
console.log('no span tag');
}
});
How can I get the html of a highlighted text and change it accordingly? It would really mean a lot if you could help me through. Thank you.
Demo
Do this,
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, range; i < len; ++i) {
range = sel.getRangeAt(i);
if (range.startContainer === range.endContainer
&& range.startContainer.nodeType === Node.TEXT_NODE
&& range.startOffset === 0
&& range.endOffset === range.startContainer.length) {
range.selectNode(range.startContainer.parentElement);
}
container.appendChild(range.cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}

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 Copy the HTML Selection String with TextFormat information

I have seen answers given for Copying HTML using javascript. Almost all answers were to use clonecontents as Below
function() {
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;
}
}
return html;
};
But here if the tags are there in the selection region, then only formatting is getting copied, else it will be copied as a Text itself. I want to copy the formatting information associated with the selection. How can i achieve this.
Test it can select with parent node
function(){
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var Node=sel.focusNode.parentNode.cloneNode(true);
//console.log(Node);
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
//
Node.innerHTML=html;
var co = document.createElement("div");
co.appendChild(Node);
html=co.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}

How do I insert some text where the cursor is? [duplicate]

This question already has answers here:
Inserting a text where cursor is using Javascript/jquery
(13 answers)
Closed 7 years ago.
I'm upgrading some Javascript which works on IE. However, I'm having some problems.
Heres the IE code:
var range = document.getElementById('text').contentWindow.window
.document.getElementById('Content').createTextRange();
var textObj = document.getElementById('text').contentWindow.window
.document.getElementById('Content');
var textFieldValue = theSmile;
if (range && textObj.CursorPos) {
var CursorPos = textObj.CursorPos;
CursorPos.text = CursorPos.text.charAt(CursorPos.text.length - 1)
== ' ' ?' ' + textFieldValue : textFieldValue;
} else {
textObj.value = textFieldValue;
}
I've tried replacing CreateTextRange with CreateRange for non-IE browsers, but this doesn't help. With code like this:
var range;
var textObj;
var iframeEl = document.getElementById('text');
if (iframeEl.contentDocument) { // DOM
range = iframeEl.contentDocument.getElementById('Content').createRange;
textObj= iframeEl.contentDocument.getElementById('Content');
} else if (iframeEl.contentWindow) { // IE win
range = iframeEl.contentWindow.document.getElementById('Content')
.createTextRange;
textObj= iframeEl.contentWindow.document.getElementById('Content');
}
Here's a function to insert text at the cursor in a textarea or text input, which is what it seems you have. It works in all major browsers:
function insertTextAtCursor(el, text) {
var val = el.value, endIndex, range, doc = el.ownerDocument;
if (typeof el.selectionStart == "number"
&& typeof el.selectionEnd == "number") {
endIndex = el.selectionEnd;
el.value = val.slice(0, endIndex) + text + val.slice(endIndex);
el.selectionStart = el.selectionEnd = endIndex + text.length;
} else if (doc.selection != "undefined" && doc.selection.createRange) {
el.focus();
range = doc.selection.createRange();
range.collapse(false);
range.text = text;
range.select();
}
}
You can use it as follows:
var iframeWin = document.getElementById('text').contentWindow;
var textObj = iframeWin.document.getElementById('Content');
insertTextAtCursor(textObj, "foo");

Categories