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

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
}
}

Related

Replace text and following letter with other text

I am making a syntax highlighter in jQuery, and I would like to be able to show escap-tion (e.g. \n). Currently, my code just replaces \ with <span style="color:#3b73e3;">\\</span> (the first \ is for... well... escap-tion). What I would like is if it could replace \ and the following letter with <span style="color:#3b73e3;">\\(the escaped letter)</span>.
The current .replace code:
String.prototype.replaceAllTxt = function() {
return this.toString().replace(/\$slc/g, '*select')
.replace(/\$/g, "!dol")
.replace(/:/g, "$cln")
.replace(/\//g, "$slh")
.replace(/\./g, "$per")
.replace(/#/g, "$at")
.replace(/%/g, "$prc")
.replace(/"/g, "*")
.replace('*select', '<span id="select"></span>')
.replace(/\*([^\*]+)\*/g, '<span style="color:#16630D">"$1"</span>')
.replace(/\$cln/g, '<span style="color:#ff755d">:</span>')
.replace(/\$at/g, '<span style="color:#ff26b6">#</span>')
.replace(/\$prc/g, '<span style="color:#9e26ff">%</span>')
.replace(/\$per/g, '<span style="color:#00bbff">.</span>')
.replace(/\$slh/g, '<span style="color:#3b73e3;">/</span>')
.replace(/\\/g, '<span style="color:#3b73e3;">\\</span>')
.replace(/!dol/g, '<span style="color:#9b1940;font-weight:bold;">$</span>')
.replace(/\$cln/g, ":")
.replace(/\$slh/g, "/")
.replace(/\$per/g, ".")
.replace(/\$at/g, "#")
.replace(/\$prc/g, "%")
.replace(/\*/g, '"')
.replace(/!dol/g, '$');
};
Everything so far:
String.prototype.replaceAllTxt = function() {
return this.toString().replace(/\$slc/g, '*select')
.replace(/\$/g, "!dol")
.replace(/:/g, "$cln")
.replace(/\//g, "$slh")
.replace(/\./g, "$per")
.replace(/#/g, "$at")
.replace(/%/g, "$prc")
.replace(/"/g, "*")
.replace('*select', '<span id="select"></span>')
.replace(/\*([^\*]+)\*/g, '<span style="color:#16630D">"$1"</span>')
.replace(/\$cln/g, '<span style="color:#ff755d">:</span>')
.replace(/\$at/g, '<span style="color:#ff26b6">#</span>')
.replace(/\$prc/g, '<span style="color:#9e26ff">%</span>')
.replace(/\$per/g, '<span style="color:#00bbff">.</span>')
.replace(/\$slh/g, '<span style="color:#3b73e3;">/</span>')
.replace(/\\/g, '<span style="color:#3b73e3;">\\</span>')
.replace(/!dol/g, '<span style="color:#9b1940;font-weight:bold;">$</span>')
.replace(/\$cln/g, ":")
.replace(/\$slh/g, "/")
.replace(/\$per/g, ".")
.replace(/\$at/g, "#")
.replace(/\$prc/g, "%")
.replace(/\*/g, '"')
.replace(/!dol/g, '$');
};
function replaceText(oldText, newText, node){
node = node || document.body; // base node
var childs = node.childNodes, i = 0;
while(node = childs[i]){
if (node.nodeType == 3){ // text node found, do the replacement
if (node.textContent) {
node.textContent = node.textContent.replace(oldText, newText);
} else { // support to IE
node.nodeValue = node.nodeValue.replace(oldText, newText);
}
} else { // not a text mode, look forward
replaceText(oldText, newText, node);
}
i++;
}
}
function codeBox(el) {
pasteHtmlAtCaret('$slc');
$(el).css('color', '#153A7D').each(function () {
setTimeout(function() {
var txt = $(el).text();
var newtxt = txt.replaceAllTxt();
$(el).html(newtxt);
});
});
setTimeout(function() {
$('#select').focus().select().remove();
}, 1);
}
$.fn.codeBox = function () {
$(this).css('color', '#153A7D').each(function () {
var txt = $(this).text();
var newtxt = txt.replaceAllTxt();
$(this).html(newtxt);
});
};
function wait(run, ms) {
setTimeout(run(),ms);
}
function loop (run, ms) {
setInterval(run(), ms);
}
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
function pasteHtmlAtCaret(html, selectPastedContent) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// only relatively recently standardized and is not supported in
// some browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) ) {
lastNode = frag.appendChild(node);
}
var firstNode = frag.firstChild;
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
if (selectPastedContent) {
range.setStartBefore(firstNode);
} else {
range.collapse(true);
}
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if ( (sel = document.selection) && sel.type != "Control") {
// IE < 9
var originalRange = sel.createRange();
originalRange.collapse(true);
sel.createRange().pasteHTML(html);
if (selectPastedContent) {
range = sel.createRange();
range.setEndPoint("StartToStart", originalRange);
range.select();
}
}
}
function selectElementText(el, win) {
win = win || window;
var doc = win.document, sel, range;
if (win.getSelection && doc.createRange) {
sel = win.getSelection();
range = doc.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
} else if (doc.body.createTextRange) {
range = doc.body.createTextRange();
range.moveToElementText(el);
range.select();
}
}
$(document).ready(function() {
$('p').each(function () {
$(this).html($(this).html().replace(/\n/g, "<br>"));
});
//$('code').each(function() {
// $(this).before('<span class="code" style="font-family:Source Code Pro, monospace;background-color:#e8e8e8;">'+$(this).text()+'</span>').remove();
// c
// console.log ('code')
//});
$('code').codeBox();
$("#edit").keypress(function() {
setTimeout(function() {
codeBox("#edit");
}, 1);
});
$('#highlight').click(function() {
$("#code").codeBox();
})
});
.code {
font-family:'Source Code Pro', monospace;
}
<script src="http://code.jquery.com/jquery-2.1.4.js"></script>
<pre data-syntax="default" id="code">$(document).ready(function() {
alert ("The highlighting is ready. Email me at admin#example for more details.\nThis page has a 100% chance of loading.";
}
I would like for \n to look like </pre><span style="color:#3b73e3;">\n</span>, the same for \anything.
<div class="button" id="highlight">Highlight!</div>
JsFiddle: http://jsfiddle.net/zoweb/zuc5f7w8/
NOTE: Some of the functions in the snippet above are taken from other SO answers, and many are not being used.
You want to capture the next symbol, and this is done by using parentheses:
console.log("stuff\\ntext".replace(/\\(\w)/g, '<span style="color:#3b73e3;">\\$1</span>'));
This will only work for escaped sequences ("\\n"), because plain '\n' is one character.

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();
}
}

How to select text in IE?

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

search page function for internet explorer

I need to put a search page function in the site that I'm working on. I found one online and it works great in Firefox and Chrome but not at all in IE. I think the fact that I didn't write this code is making it particularly hard to debug. Any help or guidance is appreciated!
HTML
<form id="f1" name="f1" action="javascript:void(0)" onsubmit="searchpage()" >
<input id="t1" type="text" name="t1" />
<input id="button" type="submit" value="FIND" name="b1" onclick="searchpage()" />
</form>
JAVASCRIPT
function searchpage() {
if (document.getElementById("t1").value != null && this.document.getElementById("t1").value != '') parent.findString(document.getElementById("t1").value);
return false;
}
var TRange = null;
function findString(str) {
if (parseInt(navigator.appVersion) < 4) return;
var strFound;
if (window.find) {
// CODE FOR BROWSERS THAT SUPPORT window.find
strFound = self.find(str);
if (!strFound) {
strFound = self.find(str, 0, 1);
while (self.find(str, 0, 1)) continue;
}
}
else if (navigator.appName.indexOf("Microsoft") != -1) {
// EXPLORER-SPECIFIC CODE
if (TRange != null) {
TRange.collapse(false);
strFound = TRange.findText(str);
if (strFound) TRange.select();
}
if (TRange == null || strFound == 0) {
TRange = self.document.body.createTextRange();
strFound = TRange.findText(str);
if (strFound) TRange.select();
}
}
else if (navigator.appName == "Opera") {
alert("Opera browsers not supported, sorry...")
return;
}
if (!strFound) alert("String '" + str + "' not found!") return;
}​
it is also important to note that while this works in Firefox and Chrome, the "string not found!" alert box doesn't work
Here's a version dapted from another answer of mine.
Demo: http://jsfiddle.net/MRp2G/5/
Code:
function doSearch(text) {
var sel;
if (window.find && window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount > 0) {
sel.collapseToEnd();
}
window.find(text);
} else if (document.selection && document.body.createTextRange) {
sel = document.selection;
var textRange;
if (sel.type == "Text") {
textRange = sel.createRange();
textRange.collapse(false);
} else {
textRange = document.body.createTextRange();
textRange.collapse(true);
}
if (textRange.findText(text)) {
textRange.select();
}
}
}

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>

Categories