Get Selected HTML in Browser via JavaScript

Get Selected HTML in browser via Javascript

Here is some code I found somewhere but I lost the actual link and this seems to work.

http://jsfiddle.net/Y4BBq/

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>The serialized HTML of a selection in Mozilla and IE</title>
<script type="text/javascript">
function getHTMLOfSelection () {
var range;
if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
return range.htmlText;
}
else if (window.getSelection) {
var selection = window.getSelection();
if (selection.rangeCount > 0) {
range = selection.getRangeAt(0);
var clonedSelection = range.cloneContents();
var div = document.createElement('div');
div.appendChild(clonedSelection);
return div.innerHTML;
}
else {
return '';
}
}
else {
return '';
}
}
</script>
</head>
<body>
<div>
<p>Some text to <span class="test">test</span> the selection on.
Kibology for <b>all</b><br />. All <i>for</i> Kibology.
</p>
</div>
<form action="">
<p>
<input type="button" value="show HTML of selection"
onclick="this.form.output.value = getHTMLOfSelection();">
</p>
<p>
<textarea name="output" rows="5" cols="80"></textarea>
</p>
</form>
</body>
</html>

Sample Image

There are some issues with the code (I tested with safari) where it doesn't return the exact selection.

Sample Image
Sample Image
Sample Image

How to get selected html text with javascript?

In IE <= 10 browsers, it's:

document.selection.createRange().htmlText

As @DarrenMB pointed out IE11 no longer supports this. See this answer for reference.


In non-IE browsers, I just tried playing with this... this seems to work, WILL have side effects from breaking nodes in half and creating an extra span, but it's a starting point:

var range = window.getSelection().getRangeAt(0),
content = range.extractContents(),
span = document.createElement('SPAN');

span.appendChild(content);
var htmlContent = span.innerHTML;

range.insertNode(span);

alert(htmlContent);

Unfortunately, I can't seem to put the node back as it was (since you can be pulling half the text from a span, for instance).

how to get selected DOM using javascript if selected text is HTML?

You can try this approach.. (if only you've direct text node in your div)

window.getSelection().focusNode.parentElement     //returns the selected element

so you can set attr like

window.getSelection().focusNode.parentElement.setAttribute('data-id', 'id-1');

You can wrap it in a 'mouseup' event with your current div

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="myDiv">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id natus voluptatibus eum explicabo soluta excepturi?
</div>
<div id="myDiv2">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id natus voluptatibus eum explicabo soluta excepturi?
</div>

<script>
var myDiv = document.getElementById('myDiv')
myDiv.addEventListener('mouseup', function(){
window.getSelection().focusNode.parentElement.setAttribute('data-id', 'id-1');
})
</script>
</body>
</html>

Or it is best approach to add attr to selected 'div' only, if there is many divs

var div = document.querySelectorAll('div')
for(var i = 0; i < div.length; i++){
div[i].addEventListener('mouseup', function(){
window.getSelection().focusNode.parentElement.setAttribute('data-id', 'id-1');
}, false)
}

Getting selected text in a browser, cross-platform

Have a look at jQuery and the wrapSelection plugin. It may be what you are looking for.

Get Selected Text on HTML page using jQuery

Getting selected text from a textarea requires a different API from getting the selected text in the main text of the page in most browsers. You should use the textarea's selectionStart and selectionEnd properties. This method will work for text inputs too:

function getSelectedText(el) {
var sel, range;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
return el.value.slice(el.selectionStart, el.selectionEnd);
} else if (
(sel = document.selection) &&
sel.type == "Text" &&
(range = sel.createRange()).parentElement() == el) {
return range.text;
}
return "";
}

Example:

function getSelectedText(el) {  var sel, range;  if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {    return el.value.slice(el.selectionStart, el.selectionEnd);  } else if (    (sel = document.selection) &&    sel.type == "Text" &&    (range = sel.createRange()).parentElement() == el) {    return range.text;  }  return "";}
window.onload = function() { document.getElementById("ta").onselect = function() { alert("Selected text: " + getSelectedText(this)); };};
<textarea id="ta" rows="5" cols="50">Please select some text in here</textarea>

get selected text's html in div

Select text and store it in variable called mytext.

if (!window.x) {
x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}

$(function() {
$(document).bind("mouseup", function() {
var mytext = x.Selector.getSelected();
alert(mytext);
});
});

Check working example at http://jsfiddle.net/YstZn/1/



Related Topics



Leave a reply



Submit