Monday, December 19, 2011

Determining What Element is Selected (Part 1)

Element selections are a similar to text selections in some ways but differ in others.

Use the document property ElementSelection to get the current element selection.

Just as text selections consist of a text range with beginning and ending text locations, element selections are an element range with beginning and ending element locations.

The difference between the two emerges when you look at the element locations that define the starting and ending points for an element selection. Unlike a text location which is typically a paragraph and an offset from the start of that paragraph, an element location consists of:
  • A parent element
  • A child element
  • An offset which is relative to the containing element.
The following script demonstrates how to work with the beginning of an element selection. It can also be used as a tool for understanding the meaning of parent and child element in this context.

//Returns the element definition name
function getElementName(elem) {
    var elemDef, name = null;

    elemDef = elem.ElementDef;
    if (elemDef.ObjectValid()) {
        name = elemDef.Name;
    return name;

//Returns location information for the current element selection
function getElementSelectionStart(doc) {
    var eLoc, eRange, locInfo;
    eRange = doc.ElementSelection;
    locInfo = {
        'parent' : eRange.beg.parent,
        'child' : eRange.beg.child,
        'offset' : eRange.beg.offset
    return locInfo;

var doc, elem, pName = null, cName = null, locInfo;
doc = app.ActiveDoc;

locInfo = getElementSelectionStart(doc);

if (locInfo.parent.ObjectValid()) {
    pName = getElementName(locInfo.parent);
if (locInfo.child.ObjectValid()) {
    cName = getElementName(locInfo.child);
Alert("Parent is " + pName + ", child is " + cName + " and offset is " + locInfo.offset,

The first two test shown deal with the case where an entire element is selected. In these cases, the offset from the start of the element is always 0.

In the case where the root element is selected, the parent element is null and the child is the root element:

If an element other than the root element is selected, the child is the selected element and the parent is the parent of that child element.

This final example has an insertion point between the "o" and the "t" in "Motor" in the first document paragraph. In this case, the parent element is p (the paragraph element), and there is no child element. The offset from the start of p is 2.

No comments:

Post a Comment