Peter Wone
Peter Wone

Reputation: 18765

Expand document.getSelection() to entire paragraph

With IE, this js code only works when the selection has a non-zero length:

document.execCommand("FormatBlock",false,tag);

Getting the containing node is trivial:

var node = document.getSelection().anchorNode;

but I don't really understand how to set the selection to encompass all the text of this node.

The single biggest source of confusion for me is ranges, selections, the relationship between the two and how you use them together in the context of a contenteditable div which seems to have different rules from input controls. I tried searching for a tutorial but "selection" and "range" are broad terms and I haven't found anything good yet.

I found this in msdn but due to my incomprehension of ranges and selections I couldn't see how to apply it. Here's a code snippet and prefatory text from that page.

When applied to a TextRange object, the select method causes the current object to be highlighted. The following function uses the findText method to set the current object to the text in the TextRange object. The function assumes an element that contains the text string "text here".

function TextRangeSelect() {
  var r = document.body.createTextRange();
  r.findText("text here");
  r.select();
}

From that I wrote the following, but it causes the whole document to be selected.

var sel = document.getSelection();
var r = document.body.createTextRange();
r.findText(sel.anchorNode);
r.select();

Upvotes: 1

Views: 297

Answers (1)

Peter Wone
Peter Wone

Reputation: 18765

This will expand the selection to the whole paragraph.

sel.selectAllChildren(sel.anchorNode.parentNode);

Since you only need to do this for internet explorer, this is your all-browsers version

if (document.getSelection) {
  var sel = document.getSelection();
  var node = typeof sel.anchorNode.data == "string" ? 
    sel.anchorNode.parentNode : 
    sel.anchorNode;
  sel.selectAllChildren(node);
}

Upvotes: 1

Related Questions