How to Get Selected HTML Text with JavaScript

Get selected option text with JavaScript

Try options

function myNewFunction(sel) {  alert(sel.options[sel.selectedIndex].text);}
<select id="box1" onChange="myNewFunction(this);">  <option value="98">dog</option>  <option value="7122">cat</option>  <option value="142">bird</option></select>

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

How to get selected text with JavaScript

One problem that you may well be experiencing is that in some browsers (notably IE), by the time the button's click event fires, the selection has been destroyed. You can fix this by using the mousedown event instead (which still allows the selection to be destroyed, but only after the event has been handled), or by making the button unselectable.

I assume your button is not an actual button input, because this behaviour only happens for regular elements.

Demo: http://jsfiddle.net/L9bvU/1/

function GetSelectedText () {    if (window.getSelection) {  // all browsers, except IE before version 9        var range = window.getSelection ();        alert (range.toString ());    }     else {        if (document.selection.createRange) { // Internet Explorer            var range = document.selection.createRange ();            alert (range.text);        }    }}
span {    background-color: #ccc;    padding: 3px;    border: solid gray 1px;    }
*[unselectable="on"] { -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none;
/* Introduced in IE 10. See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/ */ -ms-user-select: none; user-select: none;}
<div contenteditable="true">Please select some of this text and press a button below</div>
<span onclick="GetSelectedText()">Click</span><span onmousedown="GetSelectedText()">Mousedown</span><span unselectable="on" onclick="GetSelectedText()">Click, unselectable</span>

How to get Javascript Select box's selected text

this.options[this.selectedIndex].innerHTML

should provide you with the "displayed" text of the selected item. this.value, like you said, merely provides the value of the value attribute.

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