tundoopani
tundoopani

Reputation: 265

How do I select (get range or selection object) an element in a contenteditable div if I know the element ID?

I have this contenteditable element:

<div id="editMe" contenteditable="true">
     There is some text here.
     <span id="selectThisText">This is the target text.</span>
     And some here.
</div>

I want to use Javascript to select (get range object) the contents of #selectThisText. How do I get the range of the content in that element?

Thanks in advance!

Upvotes: 4

Views: 5991

Answers (3)

Smith Oscuro XAgent
Smith Oscuro XAgent

Reputation: 9

//get Selection
var selection = window.getSelection();

//get Range
var range = selection.getRangeAt(0); //where the range selection happens.

Upvotes: 0

Tim Down
Tim Down

Reputation: 324567

Create a range and use its selectNodeContents() method.

var span = document.getElementById("selectThisText");
var range = document.createRange();
range.selectNodeContents(span);

This doesn't work in IE <= 8, which doesn't support DOM Range. However, this is one case which is just as easy in old IE:

var span = document.getElementById("selectThisText");
var textRange = document.body.createTextRange();
textRange.moveToElementText(span);

Upvotes: 11

ahren
ahren

Reputation: 16961

var text = $('#selectThisText').text();

Demo: http://jsfiddle.net/5NBnP/

Upvotes: -4

Related Questions