0

I want to know what is the parent element of caret in an iframe with designMode = 'on'. The reason is that want to know if currently user is typing in a p tag.

Omid
  • 4,575
  • 9
  • 43
  • 74

1 Answers1

2

Here's a function to do this, adapted from an answer to a similar question:

function getSelectionBoundaryElement(win, isStart) {
    var range, sel, container = null;
    var doc = win.document;

    if (doc.selection) {
        // IE branch
        range = doc.selection.createRange();
        range.collapse(isStart);
        return range.parentElement();
    } else if (win.getSelection) {
        // Other browsers
        sel = win.getSelection();

        if (sel.rangeCount > 0) {
            range = sel.getRangeAt(0);
            container = range[isStart ? "startContainer" : "endContainer"];

            // Check if the container is a text node and return its parent if so
            if (container.nodeType === 3) {
                container = container.parentNode;
            }
        }
    }
    return container;
}

Example use:

var iframe = document.getElementById("your_iframe_id");
var caretElement = getSelectionBoundaryElement(iframe.contentWindow, true);
Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • I didn't understand what is `isStart` for ? – Omid Jan 28 '13 at 07:24
  • @Omid: The function also handles the general case of getting the element containing a selection boundary. `isStart` indicates whether to work with the selection start or end boundary. In the case of a collapsed selection (i.e. just a caret), these are the same, so the value of `isStart` does not matter. – Tim Down Jan 28 '13 at 09:53