How to to use document.textSelection

Submitted by: Clay Helberg Last Updated: 2006-07-29

Contrary to the name, document.textSelection gives you the full selection, including markup, as a DOM Range object. Note that a popup box converts the Range to a string when it creates the message (as if using the toString method, which only includes text nodes). But you can use the usual methods to access nodes in the range and it should work. To convince yourself, try this: txt = document.textSelection;

Application.alert(textSelection.toMarkupString);

Note that toMarkupString is not a W3C Range method, but an arbortext enhancement from the ARange interface.

You can use range.extractContents or range.cloneContents to get the contents as a DocumentFragment. The former removes the selection from the document, the latter does not. You can then use the usual tree-walking methods (childNodes, getElementById, etc.) to access the nodes there.

Here's some sample code that looks for elements in the selection, and for any it finds, it sets the type attribute value to "list-contin". Note that the approach taken here is to snip the selected content from the document, update it /ex situ/, and then reinsert the modified content.

//  // test to modify selection elements doc = Application.activeDocument; sel = doc.textSelection; content = sel.extractContents; // walk selected tree and find nodes to modify kids = content.childNodes; for (var i=0; (kid = kids.item(i)); i++) { updateStyle(kid); } sel.insertNode(content); function updateStyle(node) { // updates style of node, if appropriate, and checks child nodes recursively if (node.nodeType == node.ELEMENT_NODE) { if (node.nodeName == "p") { node.setAttribute("type","list-contin"); }    if (node.hasChildNodes) { for (var i=0; (subnode = node.childNodes.item(i)); i++) { updateStyle(subnode); }    }   } }