I was testing out the getSelection()
method, and I wanted my program to get the selected text in a certain paragraph of text and display it in a div tag. I used the following code:
var txt = document.getSelection();
document.getElementById("display").innerHTML = "The text you have selected is: " + txt + ".";
However, I want the program to only get selections made in the paragraph itself, not in the entire document. I tried using document.getElementById("id").getSelection();
but it didn't work.
How can I make it so getSelection()
only applies to a certain element?
Here's one approach, tested only in Chromium 19 (Which supports
textContent
, for Internet ExplorerinnerText
would have to be used instead):JS Fiddle demo.