Get highlighted text as a node in javascript - javascript

Working on a bit of javascript code; I'm wanting to alter the text when highlighted. The closest I've found currently is this: Get The Highlighted Selected Text. The problem with that solution though is it just gets the text that's highlighted as a string, but it's as a string. So I have the text, but I can't edit it like a node, doing innerHTML, change font, etc. It's just a string. I've got a solution that "works"™, but what is, is taking that string, and then searching for it. The problem is, if for example I highlight the string "the" in this post, I'd get a whole bunch of answers and no way to differentiate between them.
Is there a way to get selected text as a node?

You need to look for the selection (window.getSelection();)and get its range to have the right position of the selected text. Then you can apply styles by span-wrapping.
Take a look at
http://jsfiddle.net/jme11/bZb7V/

You can get an idea of how its done from this answer https://stackoverflow.com/a/3997896/5267669
Basically you get the selected text with the document.getSelection method, you delete it and in its place you insert your own content.
For example replace your selection with an H1 tag containing the text Added with js
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var h1 = document.createElement("h1");
h1.textContent = 'Added with js';
range.insertNode(h1);
}
You can select anything on this page, paste this code to the console and the selection will be replaced with an h1 tag

Related

Javascript : Replace Detect a string and replace html in a div after changing color

I am trying to change color of a part of strings. I have a list of DOM elements, and for each of them, the text can contain some hashtags. I would like to put in color all hashtags words which could be found in the text.
Here is the begin of the code :
var listOfText = document.getElementsByClassName("titleTweet");
for (var nodetext in listOfText) {
var divContent = listOfText[nodetext].innerHTML;
if (divContent.indexOf("#") !== -1) {
// Do job here
}
}
For example, divContent can be equals to "Hello my #friends ! How are you ?"
I would like to update the dom elements to put in red color the word "#friends".
I don't know how to do that using javascript or jQuery.
You can use a regexp to find the hastags and wrap them with html. Then use the .html() method to replace the original element's html with the new string.
Example snippet
$('#myDiv').replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
Working example - http://jsfiddle.net/4p4mA/1/
Edited the example to work on all divs on the page.
Note: This will only work so long as your element only contains text, because it is replacing all the child nodes with its text value.
use regex for this, find text having hashtag and replave that in span tag for each element.
$('.titleTweet').each(function(){
var $this=$(this);
$this.html($this.text()
.replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
});
See demo here
.innerHTML is a poor basis to starting replacing text. You'll want to navigate down to the text nodes and use .nodeValue to get the text. Then you can start splitting up the text nodes.

Javascript: execCommand("removeformat") doesn't strip h2 tag

I'm tweaking a wysiwyg editor, and I'm trying to create an icon which will strip selected text of h2.
In a previous version, the following command worked perfectly:
oRTE.document.execCommand("removeformat", false, "");
But in the current version, although that command successfully removes from selected text such tags as bold, underline, italics, it leaves the h2 tag intact.
(Interestingly enough, execCommand("formatblock"...) successfully creates the h2 tag.)
I'm thinking that I'm going to have to abandon execCommand and find another way, but I'm also thinking that it will be a lot more than just 1 line of code! Would be grateful for suggestions.
You can change your format to div, it's not the best solution but it works and it's short:
document.execCommand('formatBlock', false, 'div')
There is also this other solution to get the closest parent from selected text then you can unwrap it, note that this can be some tag like <b>:
var container = null;
if (document.selection) //for IE
container = document.selection.createRange().parentElement();
else {
var select = window.getSelection();
if (select.rangeCount > 0)
container = select.getRangeAt(0).startContainer.parentNode;
}
$(container).contents().unwrap(); //for jQuery1.4+
This is in accordance with the proposed W3C Editing APIs. It has a list of formatting elements, and the H# elements are not listed. These are considered structural, not simply formatting. It doesn't make any more sense to remove these tags than it would to remove UL or P.
I think you can use the Range object.
you can find it from Professional JavaScript for Web Developers 3rd Edition.
chapter 12(12.4) and chapter 14(14.5) ...
an example from that book:
var selection = frames["richedit"].getSelection();
var selectedText = selection.toString();
var range = selection.getRangeAt(0);
var span = frames["richedit"].document.createElement("span");
span.style.backgroundColor = "yellow";
range.surroundContents(span);

How to find the selection text beginning and end positions in Javascript?

I am trying to find the textual start and end of the selection. So, in the following text, if I selected "world! What a fine" from within "Hello, world! What a fine day it is!", I should get 7 as the start coordinate, and 24 as the end coordinate assuming a zero based index.
How is this achievable?
EDIT:
I am looking to find the selection of text that is not inside any <input> or <textarea> elements.
EDIT:
Decided the solution to use disabled <textarea>s
I use this:
/* Returns 3 strings, the part before the selection, the part after the selection and the selected part */
function getSelected()
{
var u = editor.val();
var start = editor.get(0).selectionStart;
var end = editor.get(0).selectionEnd;
return [u.substring(0, start), u.substring(end), u.substring(start, end)];
}
where editor is $("#editor") or whatever ID your textarea / input field may have.
Usage:
var select = getSelected()
editor.val(select[0] + '<h1>'+ select[2] + '</h1>' + select[1]);
Will wrap selected text in H1. If nothing is selected it will just add empty H1, but you can add checks and functionality to your liking.
** Not tested in all browsers, works in Chrome though **
This is possible but slightly complicated with contenteditable HTML content (as opposed to text within an <input> or <textarea> element). Here's a simple cross-browser implementation:
https://stackoverflow.com/a/4812022/96100
But I know a jQuery plugin that aims your problem and much more - https://github.com/localhost/jquery-fieldselection

Get HTML of selected content

I have a UIWebView i want to introduce functionality of content(may be text or text and images) selection so that the user can email it.
Is there any way to get the HTML code for the given selection using JavaScript?
I tried the built-in clipboard of webkit but its seems not working for images selection.May be i am wrong,if there is a way please tell me.
var range, frag, sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
frag = range.cloneContents();
}
This will give you a DocumentFragment containing the selected content. You can traverse the descendants of the fragment using the usual DOM methods. If you must have a literal HTML string, you could then do the following:
var div = document.createElement("div");
div.appendChild(frag);
alert(div.innerHTML);
Note that this last part won't work if the selected contents can't be placed inside a <div> (if, say, the whole body or document was selected).

explorer: how to highlight text after using pasteHTML method?

i replace selected text with pasteHTML method (Pastes HTML text into the given text range, replacing any previous text and HTML elements in the range.) in internet explorer.
var ran = Editor.selection.createRange();
ran.pasteHTML('<span style="font-size:20px;">example</span>');
after replacing text, selection dissapears. how to highlight previous selection (text) again ? thanks
pasteHTML will delete the current selection from the document, so I assume you want to select the span you've replaced it with. To do this, add an ID to the span, move the TextRange to encompass its text and select it, as follows:
var ran = Editor.selection.createRange();
ran.pasteHTML('<span style="font-size:20px;" id="a_random_unique_id">example</span>');
var spanRange = ran.duplicate();
spanRange.moveToElementText( document.getElementById("a_random_unique_id") );
spanRange.select();

Categories

Resources